repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
decred/dcrdata
notification/ntfnhandlers.go
RegisterNodeNtfnHandlers
func RegisterNodeNtfnHandlers(dcrdClient *rpcclient.Client) *ContextualError { // Set the node client for use by signalReorg to determine the common // ancestor of two chains. nodeClient = dcrdClient // Register for block connection and chain reorg notifications. var err error if err = dcrdClient.NotifyBlocks(); err != nil { return newContextualError("block notification "+ "registration failed", err) } // Register for tx accepted into mempool ntfns if err = dcrdClient.NotifyNewTransactions(true); err != nil { return newContextualError("new transaction verbose notification registration failed", err) } // For OnNewTickets // Commented since there is a bug in rpcclient/notify.go // dcrdClient.NotifyNewTickets() if err = dcrdClient.NotifyWinningTickets(); err != nil { return newContextualError("winning ticket "+ "notification registration failed", err) } // Register a Tx filter for addresses (receiving). The filter applies to // OnRelevantTxAccepted. // TODO: register outpoints (third argument). // if len(addresses) > 0 { // if err = dcrdClient.LoadTxFilter(true, addresses, nil); err != nil { // return newContextualError("load tx filter failed", err) // } // } return nil }
go
func RegisterNodeNtfnHandlers(dcrdClient *rpcclient.Client) *ContextualError { // Set the node client for use by signalReorg to determine the common // ancestor of two chains. nodeClient = dcrdClient // Register for block connection and chain reorg notifications. var err error if err = dcrdClient.NotifyBlocks(); err != nil { return newContextualError("block notification "+ "registration failed", err) } // Register for tx accepted into mempool ntfns if err = dcrdClient.NotifyNewTransactions(true); err != nil { return newContextualError("new transaction verbose notification registration failed", err) } // For OnNewTickets // Commented since there is a bug in rpcclient/notify.go // dcrdClient.NotifyNewTickets() if err = dcrdClient.NotifyWinningTickets(); err != nil { return newContextualError("winning ticket "+ "notification registration failed", err) } // Register a Tx filter for addresses (receiving). The filter applies to // OnRelevantTxAccepted. // TODO: register outpoints (third argument). // if len(addresses) > 0 { // if err = dcrdClient.LoadTxFilter(true, addresses, nil); err != nil { // return newContextualError("load tx filter failed", err) // } // } return nil }
[ "func", "RegisterNodeNtfnHandlers", "(", "dcrdClient", "*", "rpcclient", ".", "Client", ")", "*", "ContextualError", "{", "// Set the node client for use by signalReorg to determine the common", "// ancestor of two chains.", "nodeClient", "=", "dcrdClient", "\n\n", "// Register for block connection and chain reorg notifications.", "var", "err", "error", "\n", "if", "err", "=", "dcrdClient", ".", "NotifyBlocks", "(", ")", ";", "err", "!=", "nil", "{", "return", "newContextualError", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Register for tx accepted into mempool ntfns", "if", "err", "=", "dcrdClient", ".", "NotifyNewTransactions", "(", "true", ")", ";", "err", "!=", "nil", "{", "return", "newContextualError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// For OnNewTickets", "// Commented since there is a bug in rpcclient/notify.go", "// dcrdClient.NotifyNewTickets()", "if", "err", "=", "dcrdClient", ".", "NotifyWinningTickets", "(", ")", ";", "err", "!=", "nil", "{", "return", "newContextualError", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Register a Tx filter for addresses (receiving). The filter applies to", "// OnRelevantTxAccepted.", "// TODO: register outpoints (third argument).", "// if len(addresses) > 0 {", "// \tif err = dcrdClient.LoadTxFilter(true, addresses, nil); err != nil {", "// \t\treturn newContextualError(\"load tx filter failed\", err)", "// \t}", "// }", "return", "nil", "\n", "}" ]
// RegisterNodeNtfnHandlers registers with dcrd to receive new block, // transaction and winning ticket notifications.
[ "RegisterNodeNtfnHandlers", "registers", "with", "dcrd", "to", "receive", "new", "block", "transaction", "and", "winning", "ticket", "notifications", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnhandlers.go#L27-L63
train
decred/dcrdata
notification/ntfnhandlers.go
SetSynchronousHandlers
func (q *collectionQueue) SetSynchronousHandlers(syncHandlers []func(hash *chainhash.Hash) error) { q.syncHandlers = syncHandlers }
go
func (q *collectionQueue) SetSynchronousHandlers(syncHandlers []func(hash *chainhash.Hash) error) { q.syncHandlers = syncHandlers }
[ "func", "(", "q", "*", "collectionQueue", ")", "SetSynchronousHandlers", "(", "syncHandlers", "[", "]", "func", "(", "hash", "*", "chainhash", ".", "Hash", ")", "error", ")", "{", "q", ".", "syncHandlers", "=", "syncHandlers", "\n", "}" ]
// SetSynchronousHandlers sets the slice of synchronous new block handler // functions, which are called in the order they occur in the slice.
[ "SetSynchronousHandlers", "sets", "the", "slice", "of", "synchronous", "new", "block", "handler", "functions", "which", "are", "called", "in", "the", "order", "they", "occur", "in", "the", "slice", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnhandlers.go#L92-L94
train
decred/dcrdata
notification/ntfnhandlers.go
processBlock
func (q *collectionQueue) processBlock(bh *blockHashHeight) { hash := bh.hash height := bh.height // Ensure that the received block (bh.hash, bh.height) connects to the // previously connected block (q.prevHash, q.prevHeight). if bh.prevHash != q.prevHash { log.Infof("Received block at %d (%v) does not connect to %d (%v). "+ "This is normal before reorganization.", height, hash, q.prevHeight, q.prevHash) return } start := time.Now() // Run synchronous block connected handlers in order. for _, h := range q.syncHandlers { if err := h(&hash); err != nil { log.Errorf("synchronous handler failed: %v", err) return } } // Record this block as the best block connected by the collectionQueue. q.SetPreviousBlock(hash, height) log.Debugf("Synchronous handlers of collectionQueue.processBlock() completed in %v", time.Since(start)) // Signal to mempool monitors that a block was mined. select { case NtfnChans.NewTxChan <- nil: default: } // API status update handler select { case NtfnChans.UpdateStatusNodeHeight <- uint32(height): default: } }
go
func (q *collectionQueue) processBlock(bh *blockHashHeight) { hash := bh.hash height := bh.height // Ensure that the received block (bh.hash, bh.height) connects to the // previously connected block (q.prevHash, q.prevHeight). if bh.prevHash != q.prevHash { log.Infof("Received block at %d (%v) does not connect to %d (%v). "+ "This is normal before reorganization.", height, hash, q.prevHeight, q.prevHash) return } start := time.Now() // Run synchronous block connected handlers in order. for _, h := range q.syncHandlers { if err := h(&hash); err != nil { log.Errorf("synchronous handler failed: %v", err) return } } // Record this block as the best block connected by the collectionQueue. q.SetPreviousBlock(hash, height) log.Debugf("Synchronous handlers of collectionQueue.processBlock() completed in %v", time.Since(start)) // Signal to mempool monitors that a block was mined. select { case NtfnChans.NewTxChan <- nil: default: } // API status update handler select { case NtfnChans.UpdateStatusNodeHeight <- uint32(height): default: } }
[ "func", "(", "q", "*", "collectionQueue", ")", "processBlock", "(", "bh", "*", "blockHashHeight", ")", "{", "hash", ":=", "bh", ".", "hash", "\n", "height", ":=", "bh", ".", "height", "\n\n", "// Ensure that the received block (bh.hash, bh.height) connects to the", "// previously connected block (q.prevHash, q.prevHeight).", "if", "bh", ".", "prevHash", "!=", "q", ".", "prevHash", "{", "log", ".", "Infof", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "hash", ",", "q", ".", "prevHeight", ",", "q", ".", "prevHash", ")", "\n", "return", "\n", "}", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n\n", "// Run synchronous block connected handlers in order.", "for", "_", ",", "h", ":=", "range", "q", ".", "syncHandlers", "{", "if", "err", ":=", "h", "(", "&", "hash", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Record this block as the best block connected by the collectionQueue.", "q", ".", "SetPreviousBlock", "(", "hash", ",", "height", ")", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "time", ".", "Since", "(", "start", ")", ")", "\n\n", "// Signal to mempool monitors that a block was mined.", "select", "{", "case", "NtfnChans", ".", "NewTxChan", "<-", "nil", ":", "default", ":", "}", "\n\n", "// API status update handler", "select", "{", "case", "NtfnChans", ".", "UpdateStatusNodeHeight", "<-", "uint32", "(", "height", ")", ":", "default", ":", "}", "\n", "}" ]
// processBlock calls each synchronous new block handler with the given // blockHashHeight, and then signals to the monitors that a new block was mined.
[ "processBlock", "calls", "each", "synchronous", "new", "block", "handler", "with", "the", "given", "blockHashHeight", "and", "then", "signals", "to", "the", "monitors", "that", "a", "new", "block", "was", "mined", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnhandlers.go#L119-L158
train
decred/dcrdata
notification/ntfnhandlers.go
signalReorg
func signalReorg(d ReorgData) { if nodeClient == nil { log.Errorf("The daemon RPC client for signalReorg is not configured!") return } // Determine the common ancestor of the two chains, and get the full // list of blocks in each chain back to but not including the common // ancestor. ancestor, newChain, oldChain, err := rpcutils.CommonAncestor(nodeClient, d.NewChainHead, d.OldChainHead) if err != nil { log.Errorf("Failed to determine common ancestor. Aborting reorg.") return } fullData := &txhelpers.ReorgData{ CommonAncestor: *ancestor, NewChain: newChain, NewChainHead: d.NewChainHead, NewChainHeight: d.NewChainHeight, OldChain: oldChain, OldChainHead: d.OldChainHead, OldChainHeight: d.OldChainHeight, WG: d.WG, } // Send reorg data to stakedb's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanStakeDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Send reorg data to dcrsqlite's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanWiredDB <- fullData: default: d.WG.Done() } // Send reorg data to blockdata's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanBlockData <- fullData: default: d.WG.Done() } // Send reorg data to ChainDB's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanDcrpgDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Ensure all the other chain reorgs are successful before initiating the // charts cache reorg. Send common ancestor reorg data to charts cache monitor. d.WG.Add(1) select { case NtfnChans.ReorgChartsCache <- fullData: default: d.WG.Done() } d.WG.Wait() // Update prevHash and prevHeight in collectionQueue. blockQueue.SetPreviousBlock(d.NewChainHead, int64(d.NewChainHeight)) }
go
func signalReorg(d ReorgData) { if nodeClient == nil { log.Errorf("The daemon RPC client for signalReorg is not configured!") return } // Determine the common ancestor of the two chains, and get the full // list of blocks in each chain back to but not including the common // ancestor. ancestor, newChain, oldChain, err := rpcutils.CommonAncestor(nodeClient, d.NewChainHead, d.OldChainHead) if err != nil { log.Errorf("Failed to determine common ancestor. Aborting reorg.") return } fullData := &txhelpers.ReorgData{ CommonAncestor: *ancestor, NewChain: newChain, NewChainHead: d.NewChainHead, NewChainHeight: d.NewChainHeight, OldChain: oldChain, OldChainHead: d.OldChainHead, OldChainHeight: d.OldChainHeight, WG: d.WG, } // Send reorg data to stakedb's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanStakeDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Send reorg data to dcrsqlite's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanWiredDB <- fullData: default: d.WG.Done() } // Send reorg data to blockdata's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanBlockData <- fullData: default: d.WG.Done() } // Send reorg data to ChainDB's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanDcrpgDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Ensure all the other chain reorgs are successful before initiating the // charts cache reorg. Send common ancestor reorg data to charts cache monitor. d.WG.Add(1) select { case NtfnChans.ReorgChartsCache <- fullData: default: d.WG.Done() } d.WG.Wait() // Update prevHash and prevHeight in collectionQueue. blockQueue.SetPreviousBlock(d.NewChainHead, int64(d.NewChainHeight)) }
[ "func", "signalReorg", "(", "d", "ReorgData", ")", "{", "if", "nodeClient", "==", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "// Determine the common ancestor of the two chains, and get the full", "// list of blocks in each chain back to but not including the common", "// ancestor.", "ancestor", ",", "newChain", ",", "oldChain", ",", "err", ":=", "rpcutils", ".", "CommonAncestor", "(", "nodeClient", ",", "d", ".", "NewChainHead", ",", "d", ".", "OldChainHead", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "fullData", ":=", "&", "txhelpers", ".", "ReorgData", "{", "CommonAncestor", ":", "*", "ancestor", ",", "NewChain", ":", "newChain", ",", "NewChainHead", ":", "d", ".", "NewChainHead", ",", "NewChainHeight", ":", "d", ".", "NewChainHeight", ",", "OldChain", ":", "oldChain", ",", "OldChainHead", ":", "d", ".", "OldChainHead", ",", "OldChainHeight", ":", "d", ".", "OldChainHeight", ",", "WG", ":", "d", ".", "WG", ",", "}", "\n\n", "// Send reorg data to stakedb's monitor.", "d", ".", "WG", ".", "Add", "(", "1", ")", "\n", "select", "{", "case", "NtfnChans", ".", "ReorgChanStakeDB", "<-", "fullData", ":", "default", ":", "d", ".", "WG", ".", "Done", "(", ")", "\n", "}", "\n", "d", ".", "WG", ".", "Wait", "(", ")", "\n\n", "// Send reorg data to dcrsqlite's monitor.", "d", ".", "WG", ".", "Add", "(", "1", ")", "\n", "select", "{", "case", "NtfnChans", ".", "ReorgChanWiredDB", "<-", "fullData", ":", "default", ":", "d", ".", "WG", ".", "Done", "(", ")", "\n", "}", "\n\n", "// Send reorg data to blockdata's monitor.", "d", ".", "WG", ".", "Add", "(", "1", ")", "\n", "select", "{", "case", "NtfnChans", ".", "ReorgChanBlockData", "<-", "fullData", ":", "default", ":", "d", ".", "WG", ".", "Done", "(", ")", "\n", "}", "\n\n", "// Send reorg data to ChainDB's monitor.", "d", ".", "WG", ".", "Add", "(", "1", ")", "\n", "select", "{", "case", "NtfnChans", ".", "ReorgChanDcrpgDB", "<-", "fullData", ":", "default", ":", "d", ".", "WG", ".", "Done", "(", ")", "\n", "}", "\n", "d", ".", "WG", ".", "Wait", "(", ")", "\n\n", "// Ensure all the other chain reorgs are successful before initiating the", "// charts cache reorg. Send common ancestor reorg data to charts cache monitor.", "d", ".", "WG", ".", "Add", "(", "1", ")", "\n", "select", "{", "case", "NtfnChans", ".", "ReorgChartsCache", "<-", "fullData", ":", "default", ":", "d", ".", "WG", ".", "Done", "(", ")", "\n", "}", "\n", "d", ".", "WG", ".", "Wait", "(", ")", "\n\n", "// Update prevHash and prevHeight in collectionQueue.", "blockQueue", ".", "SetPreviousBlock", "(", "d", ".", "NewChainHead", ",", "int64", "(", "d", ".", "NewChainHeight", ")", ")", "\n", "}" ]
// signalReorg takes the basic reorganization data from dcrd, determines the two // chains and their common ancestor, and signals the reorg to each packages' // reorganization handler. Lastly, the collectionQueue's best block data is // updated so that it will successfully accept new blocks building on the new // chain tip.
[ "signalReorg", "takes", "the", "basic", "reorganization", "data", "from", "dcrd", "determines", "the", "two", "chains", "and", "their", "common", "ancestor", "and", "signals", "the", "reorg", "to", "each", "packages", "reorganization", "handler", ".", "Lastly", "the", "collectionQueue", "s", "best", "block", "data", "is", "updated", "so", "that", "it", "will", "successfully", "accept", "new", "blocks", "building", "on", "the", "new", "chain", "tip", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnhandlers.go#L174-L247
train
decred/dcrdata
notification/ntfnhandlers.go
superQueue
func superQueue() { for e := range anyQueue { // Do not allow new blocks to process while running reorg. Only allow // them to be processed after this reorg completes. switch et := e.(type) { case *blockHashHeight: // Process the new block. log.Infof("superQueue: Processing new block %v (height %d).", et.hash, et.height) blockQueue.processBlock(et) case ReorgData: // Process the reorg. log.Infof("superQueue: Processing reorganization from %s (height %d) to %s (height %d).", et.OldChainHead.String(), et.OldChainHeight, et.NewChainHead.String(), et.NewChainHeight) signalReorg(et) default: log.Errorf("Unknown event data type: %T", et) } } }
go
func superQueue() { for e := range anyQueue { // Do not allow new blocks to process while running reorg. Only allow // them to be processed after this reorg completes. switch et := e.(type) { case *blockHashHeight: // Process the new block. log.Infof("superQueue: Processing new block %v (height %d).", et.hash, et.height) blockQueue.processBlock(et) case ReorgData: // Process the reorg. log.Infof("superQueue: Processing reorganization from %s (height %d) to %s (height %d).", et.OldChainHead.String(), et.OldChainHeight, et.NewChainHead.String(), et.NewChainHeight) signalReorg(et) default: log.Errorf("Unknown event data type: %T", et) } } }
[ "func", "superQueue", "(", ")", "{", "for", "e", ":=", "range", "anyQueue", "{", "// Do not allow new blocks to process while running reorg. Only allow", "// them to be processed after this reorg completes.", "switch", "et", ":=", "e", ".", "(", "type", ")", "{", "case", "*", "blockHashHeight", ":", "// Process the new block.", "log", ".", "Infof", "(", "\"", "\"", ",", "et", ".", "hash", ",", "et", ".", "height", ")", "\n", "blockQueue", ".", "processBlock", "(", "et", ")", "\n", "case", "ReorgData", ":", "// Process the reorg.", "log", ".", "Infof", "(", "\"", "\"", ",", "et", ".", "OldChainHead", ".", "String", "(", ")", ",", "et", ".", "OldChainHeight", ",", "et", ".", "NewChainHead", ".", "String", "(", ")", ",", "et", ".", "NewChainHeight", ")", "\n", "signalReorg", "(", "et", ")", "\n", "default", ":", "log", ".", "Errorf", "(", "\"", "\"", ",", "et", ")", "\n", "}", "\n", "}", "\n", "}" ]
// superQueue manages the event notification queue, keeping the events in the // same order they were received by the rpcclient.NotificationHandlers, and // sending them to the appropriate handlers. This should be run as a goroutine.
[ "superQueue", "manages", "the", "event", "notification", "queue", "keeping", "the", "events", "in", "the", "same", "order", "they", "were", "received", "by", "the", "rpcclient", ".", "NotificationHandlers", "and", "sending", "them", "to", "the", "appropriate", "handlers", ".", "This", "should", "be", "run", "as", "a", "goroutine", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnhandlers.go#L257-L276
train
decred/dcrdata
exchanges/exchanges.go
Tokens
func Tokens() []string { tokens := make([]string, 0, len(BtcIndices)+len(DcrExchanges)) var token string for token = range BtcIndices { tokens = append(tokens, token) } for token = range DcrExchanges { tokens = append(tokens, token) } return tokens }
go
func Tokens() []string { tokens := make([]string, 0, len(BtcIndices)+len(DcrExchanges)) var token string for token = range BtcIndices { tokens = append(tokens, token) } for token = range DcrExchanges { tokens = append(tokens, token) } return tokens }
[ "func", "Tokens", "(", ")", "[", "]", "string", "{", "tokens", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "BtcIndices", ")", "+", "len", "(", "DcrExchanges", ")", ")", "\n", "var", "token", "string", "\n", "for", "token", "=", "range", "BtcIndices", "{", "tokens", "=", "append", "(", "tokens", ",", "token", ")", "\n", "}", "\n", "for", "token", "=", "range", "DcrExchanges", "{", "tokens", "=", "append", "(", "tokens", ",", "token", ")", "\n", "}", "\n", "return", "tokens", "\n", "}" ]
// Tokens is a new slice of available exchange tokens.
[ "Tokens", "is", "a", "new", "slice", "of", "available", "exchange", "tokens", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L169-L179
train
decred/dcrdata
exchanges/exchanges.go
IsFresh
func (depth *DepthData) IsFresh() bool { return time.Duration(time.Now().Unix()-depth.Time)* time.Second < depthDataExpiration }
go
func (depth *DepthData) IsFresh() bool { return time.Duration(time.Now().Unix()-depth.Time)* time.Second < depthDataExpiration }
[ "func", "(", "depth", "*", "DepthData", ")", "IsFresh", "(", ")", "bool", "{", "return", "time", ".", "Duration", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "-", "depth", ".", "Time", ")", "*", "time", ".", "Second", "<", "depthDataExpiration", "\n", "}" ]
// IsFresh will be true if the data is older than depthDataExpiration.
[ "IsFresh", "will", "be", "true", "if", "the", "data", "is", "older", "than", "depthDataExpiration", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L200-L203
train
decred/dcrdata
exchanges/exchanges.go
time
func (sticks Candlesticks) time() time.Time { if len(sticks) > 0 { return sticks[len(sticks)-1].Start } return time.Time{} }
go
func (sticks Candlesticks) time() time.Time { if len(sticks) > 0 { return sticks[len(sticks)-1].Start } return time.Time{} }
[ "func", "(", "sticks", "Candlesticks", ")", "time", "(", ")", "time", ".", "Time", "{", "if", "len", "(", "sticks", ")", ">", "0", "{", "return", "sticks", "[", "len", "(", "sticks", ")", "-", "1", "]", ".", "Start", "\n", "}", "\n", "return", "time", ".", "Time", "{", "}", "\n", "}" ]
// returns the start time of the last Candlestick, else the zero time,
[ "returns", "the", "start", "time", "of", "the", "last", "Candlestick", "else", "the", "zero", "time" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L219-L224
train
decred/dcrdata
exchanges/exchanges.go
needsUpdate
func (sticks Candlesticks) needsUpdate(bin candlestickKey) bool { if len(sticks) == 0 { return true } lastStick := sticks[len(sticks)-1] return time.Now().After(lastStick.Start.Add(bin.duration() * 2)) }
go
func (sticks Candlesticks) needsUpdate(bin candlestickKey) bool { if len(sticks) == 0 { return true } lastStick := sticks[len(sticks)-1] return time.Now().After(lastStick.Start.Add(bin.duration() * 2)) }
[ "func", "(", "sticks", "Candlesticks", ")", "needsUpdate", "(", "bin", "candlestickKey", ")", "bool", "{", "if", "len", "(", "sticks", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "lastStick", ":=", "sticks", "[", "len", "(", "sticks", ")", "-", "1", "]", "\n", "return", "time", ".", "Now", "(", ")", ".", "After", "(", "lastStick", ".", "Start", ".", "Add", "(", "bin", ".", "duration", "(", ")", "*", "2", ")", ")", "\n", "}" ]
// Checks whether the candlestick data for the given bin size is up-to-date.
[ "Checks", "whether", "the", "candlestick", "data", "for", "the", "given", "bin", "size", "is", "up", "-", "to", "-", "date", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L227-L233
train
decred/dcrdata
exchanges/exchanges.go
stealSticks
func (state *ExchangeState) stealSticks(top *ExchangeState) { if len(top.Candlesticks) == 0 { return } if state.Candlesticks == nil { state.Candlesticks = make(map[candlestickKey]Candlesticks) } for bin := range top.Candlesticks { _, have := state.Candlesticks[bin] if !have { state.Candlesticks[bin] = top.Candlesticks[bin] } } }
go
func (state *ExchangeState) stealSticks(top *ExchangeState) { if len(top.Candlesticks) == 0 { return } if state.Candlesticks == nil { state.Candlesticks = make(map[candlestickKey]Candlesticks) } for bin := range top.Candlesticks { _, have := state.Candlesticks[bin] if !have { state.Candlesticks[bin] = top.Candlesticks[bin] } } }
[ "func", "(", "state", "*", "ExchangeState", ")", "stealSticks", "(", "top", "*", "ExchangeState", ")", "{", "if", "len", "(", "top", ".", "Candlesticks", ")", "==", "0", "{", "return", "\n", "}", "\n", "if", "state", ".", "Candlesticks", "==", "nil", "{", "state", ".", "Candlesticks", "=", "make", "(", "map", "[", "candlestickKey", "]", "Candlesticks", ")", "\n", "}", "\n", "for", "bin", ":=", "range", "top", ".", "Candlesticks", "{", "_", ",", "have", ":=", "state", ".", "Candlesticks", "[", "bin", "]", "\n", "if", "!", "have", "{", "state", ".", "Candlesticks", "[", "bin", "]", "=", "top", ".", "Candlesticks", "[", "bin", "]", "\n", "}", "\n", "}", "\n", "}" ]
// Grab any candlesticks from the top that are not in the receiver. Candlesticks // are historical data, so never need to be discarded.
[ "Grab", "any", "candlesticks", "from", "the", "top", "that", "are", "not", "in", "the", "receiver", ".", "Candlesticks", "are", "historical", "data", "so", "never", "need", "to", "be", "discarded", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L268-L281
train
decred/dcrdata
exchanges/exchanges.go
exchangeStateFromProto
func exchangeStateFromProto(proto *dcrrates.ExchangeRateUpdate) *ExchangeState { state := &ExchangeState{ Price: proto.GetPrice(), BaseVolume: proto.GetBaseVolume(), Volume: proto.GetVolume(), Change: proto.GetChange(), Stamp: proto.GetStamp(), } updateDepth := proto.GetDepth() if updateDepth != nil { depth := &DepthData{ Time: updateDepth.Time, Bids: make([]DepthPoint, 0, len(updateDepth.Bids)), Asks: make([]DepthPoint, 0, len(updateDepth.Asks)), } for _, bid := range updateDepth.Bids { depth.Bids = append(depth.Bids, DepthPoint{ Quantity: bid.Quantity, Price: bid.Price, }) } for _, ask := range updateDepth.Asks { depth.Asks = append(depth.Asks, DepthPoint{ Quantity: ask.Quantity, Price: ask.Price, }) } state.Depth = depth } if proto.Candlesticks != nil { stickMap := make(map[candlestickKey]Candlesticks) for _, candlesticks := range proto.Candlesticks { sticks := make(Candlesticks, 0, len(candlesticks.Sticks)) for _, stick := range candlesticks.Sticks { sticks = append(sticks, Candlestick{ High: stick.High, Low: stick.Low, Open: stick.Open, Close: stick.Close, Volume: stick.Volume, Start: time.Unix(stick.Start, 0), }) } stickMap[candlestickKey(candlesticks.Bin)] = sticks } state.Candlesticks = stickMap } return state }
go
func exchangeStateFromProto(proto *dcrrates.ExchangeRateUpdate) *ExchangeState { state := &ExchangeState{ Price: proto.GetPrice(), BaseVolume: proto.GetBaseVolume(), Volume: proto.GetVolume(), Change: proto.GetChange(), Stamp: proto.GetStamp(), } updateDepth := proto.GetDepth() if updateDepth != nil { depth := &DepthData{ Time: updateDepth.Time, Bids: make([]DepthPoint, 0, len(updateDepth.Bids)), Asks: make([]DepthPoint, 0, len(updateDepth.Asks)), } for _, bid := range updateDepth.Bids { depth.Bids = append(depth.Bids, DepthPoint{ Quantity: bid.Quantity, Price: bid.Price, }) } for _, ask := range updateDepth.Asks { depth.Asks = append(depth.Asks, DepthPoint{ Quantity: ask.Quantity, Price: ask.Price, }) } state.Depth = depth } if proto.Candlesticks != nil { stickMap := make(map[candlestickKey]Candlesticks) for _, candlesticks := range proto.Candlesticks { sticks := make(Candlesticks, 0, len(candlesticks.Sticks)) for _, stick := range candlesticks.Sticks { sticks = append(sticks, Candlestick{ High: stick.High, Low: stick.Low, Open: stick.Open, Close: stick.Close, Volume: stick.Volume, Start: time.Unix(stick.Start, 0), }) } stickMap[candlestickKey(candlesticks.Bin)] = sticks } state.Candlesticks = stickMap } return state }
[ "func", "exchangeStateFromProto", "(", "proto", "*", "dcrrates", ".", "ExchangeRateUpdate", ")", "*", "ExchangeState", "{", "state", ":=", "&", "ExchangeState", "{", "Price", ":", "proto", ".", "GetPrice", "(", ")", ",", "BaseVolume", ":", "proto", ".", "GetBaseVolume", "(", ")", ",", "Volume", ":", "proto", ".", "GetVolume", "(", ")", ",", "Change", ":", "proto", ".", "GetChange", "(", ")", ",", "Stamp", ":", "proto", ".", "GetStamp", "(", ")", ",", "}", "\n\n", "updateDepth", ":=", "proto", ".", "GetDepth", "(", ")", "\n", "if", "updateDepth", "!=", "nil", "{", "depth", ":=", "&", "DepthData", "{", "Time", ":", "updateDepth", ".", "Time", ",", "Bids", ":", "make", "(", "[", "]", "DepthPoint", ",", "0", ",", "len", "(", "updateDepth", ".", "Bids", ")", ")", ",", "Asks", ":", "make", "(", "[", "]", "DepthPoint", ",", "0", ",", "len", "(", "updateDepth", ".", "Asks", ")", ")", ",", "}", "\n", "for", "_", ",", "bid", ":=", "range", "updateDepth", ".", "Bids", "{", "depth", ".", "Bids", "=", "append", "(", "depth", ".", "Bids", ",", "DepthPoint", "{", "Quantity", ":", "bid", ".", "Quantity", ",", "Price", ":", "bid", ".", "Price", ",", "}", ")", "\n", "}", "\n", "for", "_", ",", "ask", ":=", "range", "updateDepth", ".", "Asks", "{", "depth", ".", "Asks", "=", "append", "(", "depth", ".", "Asks", ",", "DepthPoint", "{", "Quantity", ":", "ask", ".", "Quantity", ",", "Price", ":", "ask", ".", "Price", ",", "}", ")", "\n", "}", "\n", "state", ".", "Depth", "=", "depth", "\n", "}", "\n\n", "if", "proto", ".", "Candlesticks", "!=", "nil", "{", "stickMap", ":=", "make", "(", "map", "[", "candlestickKey", "]", "Candlesticks", ")", "\n", "for", "_", ",", "candlesticks", ":=", "range", "proto", ".", "Candlesticks", "{", "sticks", ":=", "make", "(", "Candlesticks", ",", "0", ",", "len", "(", "candlesticks", ".", "Sticks", ")", ")", "\n", "for", "_", ",", "stick", ":=", "range", "candlesticks", ".", "Sticks", "{", "sticks", "=", "append", "(", "sticks", ",", "Candlestick", "{", "High", ":", "stick", ".", "High", ",", "Low", ":", "stick", ".", "Low", ",", "Open", ":", "stick", ".", "Open", ",", "Close", ":", "stick", ".", "Close", ",", "Volume", ":", "stick", ".", "Volume", ",", "Start", ":", "time", ".", "Unix", "(", "stick", ".", "Start", ",", "0", ")", ",", "}", ")", "\n", "}", "\n", "stickMap", "[", "candlestickKey", "(", "candlesticks", ".", "Bin", ")", "]", "=", "sticks", "\n", "}", "\n", "state", ".", "Candlesticks", "=", "stickMap", "\n", "}", "\n", "return", "state", "\n", "}" ]
// Parse an ExchangeState from a protocol buffer message.
[ "Parse", "an", "ExchangeState", "from", "a", "protocol", "buffer", "message", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L284-L334
train
decred/dcrdata
exchanges/exchanges.go
StickList
func (state *ExchangeState) StickList() string { sticks := make([]string, 0, len(state.Candlesticks)) for bin := range state.Candlesticks { sticks = append(sticks, string(bin)) } return strings.Join(sticks, ";") }
go
func (state *ExchangeState) StickList() string { sticks := make([]string, 0, len(state.Candlesticks)) for bin := range state.Candlesticks { sticks = append(sticks, string(bin)) } return strings.Join(sticks, ";") }
[ "func", "(", "state", "*", "ExchangeState", ")", "StickList", "(", ")", "string", "{", "sticks", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "state", ".", "Candlesticks", ")", ")", "\n", "for", "bin", ":=", "range", "state", ".", "Candlesticks", "{", "sticks", "=", "append", "(", "sticks", ",", "string", "(", "bin", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "sticks", ",", "\"", "\"", ")", "\n", "}" ]
// StickList is a semicolon-delimited list of available binSize.
[ "StickList", "is", "a", "semicolon", "-", "delimited", "list", "of", "available", "binSize", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L347-L353
train
decred/dcrdata
exchanges/exchanges.go
LastUpdate
func (xc *CommonExchange) LastUpdate() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastUpdate }
go
func (xc *CommonExchange) LastUpdate() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastUpdate }
[ "func", "(", "xc", "*", "CommonExchange", ")", "LastUpdate", "(", ")", "time", ".", "Time", "{", "xc", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "lastUpdate", "\n", "}" ]
// LastUpdate gets a time.Time of the last successful exchange update.
[ "LastUpdate", "gets", "a", "time", ".", "Time", "of", "the", "last", "successful", "exchange", "update", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L403-L407
train
decred/dcrdata
exchanges/exchanges.go
Hurry
func (xc *CommonExchange) Hurry(d time.Duration) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastRequest = xc.lastRequest.Add(-d) }
go
func (xc *CommonExchange) Hurry(d time.Duration) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastRequest = xc.lastRequest.Add(-d) }
[ "func", "(", "xc", "*", "CommonExchange", ")", "Hurry", "(", "d", "time", ".", "Duration", ")", "{", "xc", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "Unlock", "(", ")", "\n", "xc", ".", "lastRequest", "=", "xc", ".", "lastRequest", ".", "Add", "(", "-", "d", ")", "\n", "}" ]
// Hurry can be used to subtract some amount of time from the lastUpate // and lastFail, and can be used to de-sync the exchange updates.
[ "Hurry", "can", "be", "used", "to", "subtract", "some", "amount", "of", "time", "from", "the", "lastUpate", "and", "lastFail", "and", "can", "be", "used", "to", "de", "-", "sync", "the", "exchange", "updates", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L411-L415
train
decred/dcrdata
exchanges/exchanges.go
LastFail
func (xc *CommonExchange) LastFail() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastFail }
go
func (xc *CommonExchange) LastFail() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastFail }
[ "func", "(", "xc", "*", "CommonExchange", ")", "LastFail", "(", ")", "time", ".", "Time", "{", "xc", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "lastFail", "\n", "}" ]
// LastFail gets the last time.Time of a failed exchange update.
[ "LastFail", "gets", "the", "last", "time", ".", "Time", "of", "a", "failed", "exchange", "update", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L418-L422
train
decred/dcrdata
exchanges/exchanges.go
IsFailed
func (xc *CommonExchange) IsFailed() bool { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastFail.After(xc.lastUpdate) }
go
func (xc *CommonExchange) IsFailed() bool { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastFail.After(xc.lastUpdate) }
[ "func", "(", "xc", "*", "CommonExchange", ")", "IsFailed", "(", ")", "bool", "{", "xc", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "lastFail", ".", "After", "(", "xc", ".", "lastUpdate", ")", "\n", "}" ]
// IsFailed will be true if xc.lastFail > xc.lastUpdate.
[ "IsFailed", "will", "be", "true", "if", "xc", ".", "lastFail", ">", "xc", ".", "lastUpdate", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L425-L429
train
decred/dcrdata
exchanges/exchanges.go
LogRequest
func (xc *CommonExchange) LogRequest() { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastRequest = time.Now() }
go
func (xc *CommonExchange) LogRequest() { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastRequest = time.Now() }
[ "func", "(", "xc", "*", "CommonExchange", ")", "LogRequest", "(", ")", "{", "xc", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "Unlock", "(", ")", "\n", "xc", ".", "lastRequest", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// LogRequest sets the lastRequest time.Time.
[ "LogRequest", "sets", "the", "lastRequest", "time", ".", "Time", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L432-L436
train
decred/dcrdata
exchanges/exchanges.go
LastTry
func (xc *CommonExchange) LastTry() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastRequest }
go
func (xc *CommonExchange) LastTry() time.Time { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.lastRequest }
[ "func", "(", "xc", "*", "CommonExchange", ")", "LastTry", "(", ")", "time", ".", "Time", "{", "xc", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "lastRequest", "\n", "}" ]
// LastTry is the more recent of lastFail and LastUpdate.
[ "LastTry", "is", "the", "more", "recent", "of", "lastFail", "and", "LastUpdate", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L439-L443
train
decred/dcrdata
exchanges/exchanges.go
setLastFail
func (xc *CommonExchange) setLastFail(t time.Time) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastFail = t }
go
func (xc *CommonExchange) setLastFail(t time.Time) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastFail = t }
[ "func", "(", "xc", "*", "CommonExchange", ")", "setLastFail", "(", "t", "time", ".", "Time", ")", "{", "xc", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "Unlock", "(", ")", "\n", "xc", ".", "lastFail", "=", "t", "\n", "}" ]
// setLastFail sets the last failure time.
[ "setLastFail", "sets", "the", "last", "failure", "time", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L451-L455
train
decred/dcrdata
exchanges/exchanges.go
fail
func (xc *CommonExchange) fail(msg string, err error) { log.Errorf("%s: %s: %v", xc.token, msg, err) xc.setLastFail(time.Now()) }
go
func (xc *CommonExchange) fail(msg string, err error) { log.Errorf("%s: %s: %v", xc.token, msg, err) xc.setLastFail(time.Now()) }
[ "func", "(", "xc", "*", "CommonExchange", ")", "fail", "(", "msg", "string", ",", "err", "error", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "xc", ".", "token", ",", "msg", ",", "err", ")", "\n", "xc", ".", "setLastFail", "(", "time", ".", "Now", "(", ")", ")", "\n", "}" ]
// Log the error along with the token and an additional passed identifier.
[ "Log", "the", "error", "along", "with", "the", "token", "and", "an", "additional", "passed", "identifier", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L458-L461
train
decred/dcrdata
exchanges/exchanges.go
UpdateIndices
func (xc *CommonExchange) UpdateIndices(indices FiatIndices) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastUpdate = time.Now() xc.channels.index <- &IndexUpdate{ Token: xc.token, Indices: indices, } }
go
func (xc *CommonExchange) UpdateIndices(indices FiatIndices) { xc.mtx.Lock() defer xc.mtx.Unlock() xc.lastUpdate = time.Now() xc.channels.index <- &IndexUpdate{ Token: xc.token, Indices: indices, } }
[ "func", "(", "xc", "*", "CommonExchange", ")", "UpdateIndices", "(", "indices", "FiatIndices", ")", "{", "xc", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "Unlock", "(", ")", "\n", "xc", ".", "lastUpdate", "=", "time", ".", "Now", "(", ")", "\n", "xc", ".", "channels", ".", "index", "<-", "&", "IndexUpdate", "{", "Token", ":", "xc", ".", "token", ",", "Indices", ":", "indices", ",", "}", "\n", "}" ]
// UpdateIndices sends a bitcoin index update to the ExchangeBot.
[ "UpdateIndices", "sends", "a", "bitcoin", "index", "update", "to", "the", "ExchangeBot", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L490-L498
train
decred/dcrdata
exchanges/exchanges.go
fetch
func (xc *CommonExchange) fetch(request *http.Request, response interface{}) (err error) { resp, err := xc.client.Do(request) if err != nil { return fmt.Errorf(fmt.Sprintf("Request failed: %v", err)) } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(response) if err != nil { return fmt.Errorf(fmt.Sprintf("Failed to decode json from %s: %v", request.URL.String(), err)) } return }
go
func (xc *CommonExchange) fetch(request *http.Request, response interface{}) (err error) { resp, err := xc.client.Do(request) if err != nil { return fmt.Errorf(fmt.Sprintf("Request failed: %v", err)) } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(response) if err != nil { return fmt.Errorf(fmt.Sprintf("Failed to decode json from %s: %v", request.URL.String(), err)) } return }
[ "func", "(", "xc", "*", "CommonExchange", ")", "fetch", "(", "request", "*", "http", ".", "Request", ",", "response", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "resp", ",", "err", ":=", "xc", ".", "client", ".", "Do", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "request", ".", "URL", ".", "String", "(", ")", ",", "err", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Send the exchange request and decode the response.
[ "Send", "the", "exchange", "request", "and", "decode", "the", "response", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L501-L512
train
decred/dcrdata
exchanges/exchanges.go
state
func (xc *CommonExchange) state() *ExchangeState { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.currentState }
go
func (xc *CommonExchange) state() *ExchangeState { xc.mtx.RLock() defer xc.mtx.RUnlock() return xc.currentState }
[ "func", "(", "xc", "*", "CommonExchange", ")", "state", "(", ")", "*", "ExchangeState", "{", "xc", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "currentState", "\n", "}" ]
// A thread-safe getter for the last known ExchangeState.
[ "A", "thread", "-", "safe", "getter", "for", "the", "last", "known", "ExchangeState", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L515-L519
train
decred/dcrdata
exchanges/exchanges.go
connectWebsocket
func (xc *CommonExchange) connectWebsocket(processor WebsocketProcessor, cfg *socketConfig) error { ws, err := newSocketConnection(cfg) if err != nil { return err } xc.wsMtx.Lock() if xc.ws != nil { select { case <-xc.ws.Done(): default: xc.ws.Close() } } xc.wsProcessor = processor xc.ws = ws xc.wsMtx.Unlock() xc.startWebsocket() return nil }
go
func (xc *CommonExchange) connectWebsocket(processor WebsocketProcessor, cfg *socketConfig) error { ws, err := newSocketConnection(cfg) if err != nil { return err } xc.wsMtx.Lock() if xc.ws != nil { select { case <-xc.ws.Done(): default: xc.ws.Close() } } xc.wsProcessor = processor xc.ws = ws xc.wsMtx.Unlock() xc.startWebsocket() return nil }
[ "func", "(", "xc", "*", "CommonExchange", ")", "connectWebsocket", "(", "processor", "WebsocketProcessor", ",", "cfg", "*", "socketConfig", ")", "error", "{", "ws", ",", "err", ":=", "newSocketConnection", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "xc", ".", "wsMtx", ".", "Lock", "(", ")", "\n", "if", "xc", ".", "ws", "!=", "nil", "{", "select", "{", "case", "<-", "xc", ".", "ws", ".", "Done", "(", ")", ":", "default", ":", "xc", ".", "ws", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "xc", ".", "wsProcessor", "=", "processor", "\n", "xc", ".", "ws", "=", "ws", "\n", "xc", ".", "wsMtx", ".", "Unlock", "(", ")", "\n\n", "xc", ".", "startWebsocket", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Creates a websocket connection and starts a listen loop. Closes any existing // connections for this exchange.
[ "Creates", "a", "websocket", "connection", "and", "starts", "a", "listen", "loop", ".", "Closes", "any", "existing", "connections", "for", "this", "exchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L534-L554
train
decred/dcrdata
exchanges/exchanges.go
startWebsocket
func (xc *CommonExchange) startWebsocket() { ws, processor := xc.websocket() go func() { for { message, err := ws.Read() if err != nil { xc.setWsFail(err) return } processor(message) } }() }
go
func (xc *CommonExchange) startWebsocket() { ws, processor := xc.websocket() go func() { for { message, err := ws.Read() if err != nil { xc.setWsFail(err) return } processor(message) } }() }
[ "func", "(", "xc", "*", "CommonExchange", ")", "startWebsocket", "(", ")", "{", "ws", ",", "processor", ":=", "xc", ".", "websocket", "(", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "message", ",", "err", ":=", "ws", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "xc", ".", "setWsFail", "(", "err", ")", "\n", "return", "\n", "}", "\n", "processor", "(", "message", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// The listen loop for a websocket connection.
[ "The", "listen", "loop", "for", "a", "websocket", "connection", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L557-L569
train
decred/dcrdata
exchanges/exchanges.go
wsListening
func (xc *CommonExchange) wsListening() bool { ws, _ := xc.websocket() if ws == nil { return false } select { case <-ws.Done(): return false default: return true } }
go
func (xc *CommonExchange) wsListening() bool { ws, _ := xc.websocket() if ws == nil { return false } select { case <-ws.Done(): return false default: return true } }
[ "func", "(", "xc", "*", "CommonExchange", ")", "wsListening", "(", ")", "bool", "{", "ws", ",", "_", ":=", "xc", ".", "websocket", "(", ")", "\n", "if", "ws", "==", "nil", "{", "return", "false", "\n", "}", "\n", "select", "{", "case", "<-", "ws", ".", "Done", "(", ")", ":", "return", "false", "\n", "default", ":", "return", "true", "\n", "}", "\n", "}" ]
// Checks whether the websocketFeed Done channel is closed.
[ "Checks", "whether", "the", "websocketFeed", "Done", "channel", "is", "closed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L577-L588
train
decred/dcrdata
exchanges/exchanges.go
setWsFail
func (xc *CommonExchange) setWsFail(err error) { xc.wsMtx.Lock() defer xc.wsMtx.Unlock() log.Errorf("%s websocket error: %v", xc.token, err) xc.wsSync.err = err xc.wsSync.errCount++ xc.wsSync.fail = time.Now() }
go
func (xc *CommonExchange) setWsFail(err error) { xc.wsMtx.Lock() defer xc.wsMtx.Unlock() log.Errorf("%s websocket error: %v", xc.token, err) xc.wsSync.err = err xc.wsSync.errCount++ xc.wsSync.fail = time.Now() }
[ "func", "(", "xc", "*", "CommonExchange", ")", "setWsFail", "(", "err", "error", ")", "{", "xc", ".", "wsMtx", ".", "Lock", "(", ")", "\n", "defer", "xc", ".", "wsMtx", ".", "Unlock", "(", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "xc", ".", "token", ",", "err", ")", "\n", "xc", ".", "wsSync", ".", "err", "=", "err", "\n", "xc", ".", "wsSync", ".", "errCount", "++", "\n", "xc", ".", "wsSync", ".", "fail", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// Log the error and time, and increment the error counter.
[ "Log", "the", "error", "and", "time", "and", "increment", "the", "error", "counter", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L591-L598
train
decred/dcrdata
exchanges/exchanges.go
wsFailed
func (xc *CommonExchange) wsFailed() bool { xc.wsMtx.RLock() defer xc.wsMtx.RUnlock() return xc.wsSync.fail.After(xc.wsSync.update) }
go
func (xc *CommonExchange) wsFailed() bool { xc.wsMtx.RLock() defer xc.wsMtx.RUnlock() return xc.wsSync.fail.After(xc.wsSync.update) }
[ "func", "(", "xc", "*", "CommonExchange", ")", "wsFailed", "(", ")", "bool", "{", "xc", ".", "wsMtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "wsMtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "wsSync", ".", "fail", ".", "After", "(", "xc", ".", "wsSync", ".", "update", ")", "\n", "}" ]
// Checks whether the websocket is in a failed state.
[ "Checks", "whether", "the", "websocket", "is", "in", "a", "failed", "state", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L601-L605
train
decred/dcrdata
exchanges/exchanges.go
wsErrorCount
func (xc *CommonExchange) wsErrorCount() int { xc.wsMtx.RLock() defer xc.wsMtx.RUnlock() return xc.wsSync.errCount }
go
func (xc *CommonExchange) wsErrorCount() int { xc.wsMtx.RLock() defer xc.wsMtx.RUnlock() return xc.wsSync.errCount }
[ "func", "(", "xc", "*", "CommonExchange", ")", "wsErrorCount", "(", ")", "int", "{", "xc", ".", "wsMtx", ".", "RLock", "(", ")", "\n", "defer", "xc", ".", "wsMtx", ".", "RUnlock", "(", ")", "\n", "return", "xc", ".", "wsSync", ".", "errCount", "\n", "}" ]
// The count of errors logged since the last success-triggered reset.
[ "The", "count", "of", "errors", "logged", "since", "the", "last", "success", "-", "triggered", "reset", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L608-L612
train
decred/dcrdata
exchanges/exchanges.go
newCommonExchange
func newCommonExchange(token string, client *http.Client, reqs requests, channels *BotChannels) *CommonExchange { var tZero time.Time return &CommonExchange{ token: token, client: client, channels: channels, currentState: new(ExchangeState), lastUpdate: tZero, lastFail: tZero, lastRequest: tZero, requests: reqs, } }
go
func newCommonExchange(token string, client *http.Client, reqs requests, channels *BotChannels) *CommonExchange { var tZero time.Time return &CommonExchange{ token: token, client: client, channels: channels, currentState: new(ExchangeState), lastUpdate: tZero, lastFail: tZero, lastRequest: tZero, requests: reqs, } }
[ "func", "newCommonExchange", "(", "token", "string", ",", "client", "*", "http", ".", "Client", ",", "reqs", "requests", ",", "channels", "*", "BotChannels", ")", "*", "CommonExchange", "{", "var", "tZero", "time", ".", "Time", "\n", "return", "&", "CommonExchange", "{", "token", ":", "token", ",", "client", ":", "client", ",", "channels", ":", "channels", ",", "currentState", ":", "new", "(", "ExchangeState", ")", ",", "lastUpdate", ":", "tZero", ",", "lastFail", ":", "tZero", ",", "lastRequest", ":", "tZero", ",", "requests", ":", "reqs", ",", "}", "\n", "}" ]
// Used to initialize the embedding exchanges.
[ "Used", "to", "initialize", "the", "embedding", "exchanges", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L615-L628
train
decred/dcrdata
exchanges/exchanges.go
NewCoinbase
func NewCoinbase(client *http.Client, channels *BotChannels) (coinbase Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, CoinbaseURLs.Price, nil) if err != nil { return } coinbase = &CoinbaseExchange{ CommonExchange: newCommonExchange(Coinbase, client, reqs, channels), } return }
go
func NewCoinbase(client *http.Client, channels *BotChannels) (coinbase Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, CoinbaseURLs.Price, nil) if err != nil { return } coinbase = &CoinbaseExchange{ CommonExchange: newCommonExchange(Coinbase, client, reqs, channels), } return }
[ "func", "NewCoinbase", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "coinbase", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "CoinbaseURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "coinbase", "=", "&", "CoinbaseExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Coinbase", ",", "client", ",", "reqs", ",", "channels", ")", ",", "}", "\n", "return", "\n", "}" ]
// NewCoinbase constructs a CoinbaseExchange.
[ "NewCoinbase", "constructs", "a", "CoinbaseExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L636-L646
train
decred/dcrdata
exchanges/exchanges.go
Refresh
func (coinbase *CoinbaseExchange) Refresh() { coinbase.LogRequest() response := new(CoinbaseResponse) err := coinbase.fetch(coinbase.requests.price, response) if err != nil { coinbase.fail("Fetch", err) return } indices := make(FiatIndices) for code, floatStr := range response.Data.Rates { price, err := strconv.ParseFloat(floatStr, 64) if err != nil { coinbase.fail(fmt.Sprintf("Failed to parse float for index %s. Given %s", code, floatStr), err) continue } indices[code] = price } coinbase.UpdateIndices(indices) }
go
func (coinbase *CoinbaseExchange) Refresh() { coinbase.LogRequest() response := new(CoinbaseResponse) err := coinbase.fetch(coinbase.requests.price, response) if err != nil { coinbase.fail("Fetch", err) return } indices := make(FiatIndices) for code, floatStr := range response.Data.Rates { price, err := strconv.ParseFloat(floatStr, 64) if err != nil { coinbase.fail(fmt.Sprintf("Failed to parse float for index %s. Given %s", code, floatStr), err) continue } indices[code] = price } coinbase.UpdateIndices(indices) }
[ "func", "(", "coinbase", "*", "CoinbaseExchange", ")", "Refresh", "(", ")", "{", "coinbase", ".", "LogRequest", "(", ")", "\n", "response", ":=", "new", "(", "CoinbaseResponse", ")", "\n", "err", ":=", "coinbase", ".", "fetch", "(", "coinbase", ".", "requests", ".", "price", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "coinbase", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "indices", ":=", "make", "(", "FiatIndices", ")", "\n", "for", "code", ",", "floatStr", ":=", "range", "response", ".", "Data", ".", "Rates", "{", "price", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "floatStr", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "coinbase", ".", "fail", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "code", ",", "floatStr", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "indices", "[", "code", "]", "=", "price", "\n", "}", "\n", "coinbase", ".", "UpdateIndices", "(", "indices", ")", "\n", "}" ]
// Refresh retrieves and parses API data from Coinbase.
[ "Refresh", "retrieves", "and", "parses", "API", "data", "from", "Coinbase", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L660-L679
train
decred/dcrdata
exchanges/exchanges.go
NewCoindesk
func NewCoindesk(client *http.Client, channels *BotChannels) (coindesk Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, CoindeskURLs.Price, nil) if err != nil { return } coindesk = &CoindeskExchange{ CommonExchange: newCommonExchange(Coindesk, client, reqs, channels), } return }
go
func NewCoindesk(client *http.Client, channels *BotChannels) (coindesk Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, CoindeskURLs.Price, nil) if err != nil { return } coindesk = &CoindeskExchange{ CommonExchange: newCommonExchange(Coindesk, client, reqs, channels), } return }
[ "func", "NewCoindesk", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "coindesk", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "CoindeskURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "coindesk", "=", "&", "CoindeskExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Coindesk", ",", "client", ",", "reqs", ",", "channels", ")", ",", "}", "\n", "return", "\n", "}" ]
// NewCoindesk constructs a CoindeskExchange.
[ "NewCoindesk", "constructs", "a", "CoindeskExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L688-L698
train
decred/dcrdata
exchanges/exchanges.go
Refresh
func (coindesk *CoindeskExchange) Refresh() { coindesk.LogRequest() response := new(CoindeskResponse) err := coindesk.fetch(coindesk.requests.price, response) if err != nil { coindesk.fail("Fetch", err) return } indices := make(FiatIndices) for code, bpi := range response.Bpi { indices[code] = bpi.RateFloat } coindesk.UpdateIndices(indices) }
go
func (coindesk *CoindeskExchange) Refresh() { coindesk.LogRequest() response := new(CoindeskResponse) err := coindesk.fetch(coindesk.requests.price, response) if err != nil { coindesk.fail("Fetch", err) return } indices := make(FiatIndices) for code, bpi := range response.Bpi { indices[code] = bpi.RateFloat } coindesk.UpdateIndices(indices) }
[ "func", "(", "coindesk", "*", "CoindeskExchange", ")", "Refresh", "(", ")", "{", "coindesk", ".", "LogRequest", "(", ")", "\n", "response", ":=", "new", "(", "CoindeskResponse", ")", "\n", "err", ":=", "coindesk", ".", "fetch", "(", "coindesk", ".", "requests", ".", "price", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "coindesk", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "indices", ":=", "make", "(", "FiatIndices", ")", "\n", "for", "code", ",", "bpi", ":=", "range", "response", ".", "Bpi", "{", "indices", "[", "code", "]", "=", "bpi", ".", "RateFloat", "\n", "}", "\n", "coindesk", ".", "UpdateIndices", "(", "indices", ")", "\n", "}" ]
// Refresh retrieves and parses API data from Coindesk.
[ "Refresh", "retrieves", "and", "parses", "API", "data", "from", "Coindesk", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L725-L739
train
decred/dcrdata
exchanges/exchanges.go
NewBinance
func NewBinance(client *http.Client, channels *BotChannels) (binance Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, BinanceURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, BinanceURLs.Depth, nil) if err != nil { return } for dur, url := range BinanceURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } binance = &BinanceExchange{ CommonExchange: newCommonExchange(Binance, client, reqs, channels), } return }
go
func NewBinance(client *http.Client, channels *BotChannels) (binance Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, BinanceURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, BinanceURLs.Depth, nil) if err != nil { return } for dur, url := range BinanceURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } binance = &BinanceExchange{ CommonExchange: newCommonExchange(Binance, client, reqs, channels), } return }
[ "func", "NewBinance", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "binance", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "BinanceURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "reqs", ".", "depth", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "BinanceURLs", ".", "Depth", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "dur", ",", "url", ":=", "range", "BinanceURLs", ".", "Candlesticks", "{", "reqs", ".", "candlesticks", "[", "dur", "]", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "binance", "=", "&", "BinanceExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Binance", ",", "client", ",", "reqs", ",", "channels", ")", ",", "}", "\n", "return", "\n", "}" ]
// NewBinance constructs a BinanceExchange.
[ "NewBinance", "constructs", "a", "BinanceExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L747-L769
train
decred/dcrdata
exchanges/exchanges.go
Refresh
func (binance *BinanceExchange) Refresh() { binance.LogRequest() priceResponse := new(BinancePriceResponse) err := binance.fetch(binance.requests.price, priceResponse) if err != nil { binance.fail("Fetch price", err) return } price, err := strconv.ParseFloat(priceResponse.LastPrice, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from LastPrice=%s", priceResponse.LastPrice), err) return } baseVolume, err := strconv.ParseFloat(priceResponse.QuoteVolume, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from QuoteVolume=%s", priceResponse.QuoteVolume), err) return } dcrVolume, err := strconv.ParseFloat(priceResponse.Volume, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from Volume=%s", priceResponse.Volume), err) return } priceChange, err := strconv.ParseFloat(priceResponse.PriceChange, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from PriceChange=%s", priceResponse.PriceChange), err) return } // Get the depth chart depthResponse := new(BinanceDepthResponse) err = binance.fetch(binance.requests.depth, depthResponse) if err != nil { log.Errorf("Error retrieving depth chart data from Binance: %v", err) } depth := depthResponse.translate() // Grab the current state to check if candlesticks need updating state := binance.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range binance.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", binance.token, bin) response := new(BinanceCandlestickResponse) err := binance.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from binance for bin size %s: %v", string(bin), err) continue } sticks := response.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } binance.Update(&ExchangeState{ Price: price, BaseVolume: baseVolume, Volume: dcrVolume, Change: priceChange, Stamp: priceResponse.CloseTime / 1000, Candlesticks: candlesticks, Depth: depth, }) }
go
func (binance *BinanceExchange) Refresh() { binance.LogRequest() priceResponse := new(BinancePriceResponse) err := binance.fetch(binance.requests.price, priceResponse) if err != nil { binance.fail("Fetch price", err) return } price, err := strconv.ParseFloat(priceResponse.LastPrice, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from LastPrice=%s", priceResponse.LastPrice), err) return } baseVolume, err := strconv.ParseFloat(priceResponse.QuoteVolume, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from QuoteVolume=%s", priceResponse.QuoteVolume), err) return } dcrVolume, err := strconv.ParseFloat(priceResponse.Volume, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from Volume=%s", priceResponse.Volume), err) return } priceChange, err := strconv.ParseFloat(priceResponse.PriceChange, 64) if err != nil { binance.fail(fmt.Sprintf("Failed to parse float from PriceChange=%s", priceResponse.PriceChange), err) return } // Get the depth chart depthResponse := new(BinanceDepthResponse) err = binance.fetch(binance.requests.depth, depthResponse) if err != nil { log.Errorf("Error retrieving depth chart data from Binance: %v", err) } depth := depthResponse.translate() // Grab the current state to check if candlesticks need updating state := binance.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range binance.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", binance.token, bin) response := new(BinanceCandlestickResponse) err := binance.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from binance for bin size %s: %v", string(bin), err) continue } sticks := response.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } binance.Update(&ExchangeState{ Price: price, BaseVolume: baseVolume, Volume: dcrVolume, Change: priceChange, Stamp: priceResponse.CloseTime / 1000, Candlesticks: candlesticks, Depth: depth, }) }
[ "func", "(", "binance", "*", "BinanceExchange", ")", "Refresh", "(", ")", "{", "binance", ".", "LogRequest", "(", ")", "\n", "priceResponse", ":=", "new", "(", "BinancePriceResponse", ")", "\n", "err", ":=", "binance", ".", "fetch", "(", "binance", ".", "requests", ".", "price", ",", "priceResponse", ")", "\n", "if", "err", "!=", "nil", "{", "binance", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "price", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceResponse", ".", "LastPrice", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "binance", ".", "fail", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "priceResponse", ".", "LastPrice", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "baseVolume", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceResponse", ".", "QuoteVolume", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "binance", ".", "fail", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "priceResponse", ".", "QuoteVolume", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "dcrVolume", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceResponse", ".", "Volume", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "binance", ".", "fail", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "priceResponse", ".", "Volume", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "priceChange", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceResponse", ".", "PriceChange", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "binance", ".", "fail", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "priceResponse", ".", "PriceChange", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Get the depth chart", "depthResponse", ":=", "new", "(", "BinanceDepthResponse", ")", "\n", "err", "=", "binance", ".", "fetch", "(", "binance", ".", "requests", ".", "depth", ",", "depthResponse", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "depth", ":=", "depthResponse", ".", "translate", "(", ")", "\n\n", "// Grab the current state to check if candlesticks need updating", "state", ":=", "binance", ".", "state", "(", ")", "\n\n", "candlesticks", ":=", "map", "[", "candlestickKey", "]", "Candlesticks", "{", "}", "\n", "for", "bin", ",", "req", ":=", "range", "binance", ".", "requests", ".", "candlesticks", "{", "oldSticks", ",", "found", ":=", "state", ".", "Candlesticks", "[", "bin", "]", "\n", "if", "!", "found", "||", "oldSticks", ".", "needsUpdate", "(", "bin", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "binance", ".", "token", ",", "bin", ")", "\n", "response", ":=", "new", "(", "BinanceCandlestickResponse", ")", "\n", "err", ":=", "binance", ".", "fetch", "(", "req", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "bin", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "sticks", ":=", "response", ".", "translate", "(", ")", "\n\n", "if", "!", "found", "||", "sticks", ".", "time", "(", ")", ".", "After", "(", "oldSticks", ".", "time", "(", ")", ")", "{", "candlesticks", "[", "bin", "]", "=", "sticks", "\n", "}", "\n", "}", "\n", "}", "\n\n", "binance", ".", "Update", "(", "&", "ExchangeState", "{", "Price", ":", "price", ",", "BaseVolume", ":", "baseVolume", ",", "Volume", ":", "dcrVolume", ",", "Change", ":", "priceChange", ",", "Stamp", ":", "priceResponse", ".", "CloseTime", "/", "1000", ",", "Candlesticks", ":", "candlesticks", ",", "Depth", ":", "depth", ",", "}", ")", "\n", "}" ]
// Refresh retrieves and parses API data from Binance.
[ "Refresh", "retrieves", "and", "parses", "API", "data", "from", "Binance", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L936-L1005
train
decred/dcrdata
exchanges/exchanges.go
NewBittrex
func NewBittrex(client *http.Client, channels *BotChannels) (bittrex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, BittrexURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, BittrexURLs.Depth, nil) if err != nil { return } for dur, url := range BittrexURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } bittrex = &BittrexExchange{ CommonExchange: newCommonExchange(Bittrex, client, reqs, channels), MarketName: "BTC-DCR", } return }
go
func NewBittrex(client *http.Client, channels *BotChannels) (bittrex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, BittrexURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, BittrexURLs.Depth, nil) if err != nil { return } for dur, url := range BittrexURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } bittrex = &BittrexExchange{ CommonExchange: newCommonExchange(Bittrex, client, reqs, channels), MarketName: "BTC-DCR", } return }
[ "func", "NewBittrex", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "bittrex", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "BittrexURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "reqs", ".", "depth", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "BittrexURLs", ".", "Depth", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "dur", ",", "url", ":=", "range", "BittrexURLs", ".", "Candlesticks", "{", "reqs", ".", "candlesticks", "[", "dur", "]", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "bittrex", "=", "&", "BittrexExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Bittrex", ",", "client", ",", "reqs", ",", "channels", ")", ",", "MarketName", ":", "\"", "\"", ",", "}", "\n", "return", "\n", "}" ]
// NewBittrex constructs a BittrexExchange.
[ "NewBittrex", "constructs", "a", "BittrexExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1014-L1038
train
decred/dcrdata
exchanges/exchanges.go
makePts
func (pts BittrexDepthArray) makePts() []DepthPoint { depth := make([]DepthPoint, 0, len(pts)) for _, pt := range pts { depth = append(depth, DepthPoint{ Quantity: pt.Quantity, Price: pt.Rate, }) } return depth }
go
func (pts BittrexDepthArray) makePts() []DepthPoint { depth := make([]DepthPoint, 0, len(pts)) for _, pt := range pts { depth = append(depth, DepthPoint{ Quantity: pt.Quantity, Price: pt.Rate, }) } return depth }
[ "func", "(", "pts", "BittrexDepthArray", ")", "makePts", "(", ")", "[", "]", "DepthPoint", "{", "depth", ":=", "make", "(", "[", "]", "DepthPoint", ",", "0", ",", "len", "(", "pts", ")", ")", "\n", "for", "_", ",", "pt", ":=", "range", "pts", "{", "depth", "=", "append", "(", "depth", ",", "DepthPoint", "{", "Quantity", ":", "pt", ".", "Quantity", ",", "Price", ":", "pt", ".", "Rate", ",", "}", ")", "\n", "}", "\n", "return", "depth", "\n", "}" ]
// Translate the bittrex list to DepthPoints.
[ "Translate", "the", "bittrex", "list", "to", "DepthPoints", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1080-L1089
train
decred/dcrdata
exchanges/exchanges.go
translate
func (r *BittrexDepthResponse) translate() *DepthData { if r == nil { return nil } if !r.Success { log.Errorf("Bittrex depth result error: %s", r.Message) return nil } depth := new(DepthData) depth.Time = time.Now().Unix() depth.Asks = r.Result.Sell.makePts() depth.Bids = r.Result.Buy.makePts() return depth }
go
func (r *BittrexDepthResponse) translate() *DepthData { if r == nil { return nil } if !r.Success { log.Errorf("Bittrex depth result error: %s", r.Message) return nil } depth := new(DepthData) depth.Time = time.Now().Unix() depth.Asks = r.Result.Sell.makePts() depth.Bids = r.Result.Buy.makePts() return depth }
[ "func", "(", "r", "*", "BittrexDepthResponse", ")", "translate", "(", ")", "*", "DepthData", "{", "if", "r", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "!", "r", ".", "Success", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "Message", ")", "\n", "return", "nil", "\n", "}", "\n", "depth", ":=", "new", "(", "DepthData", ")", "\n", "depth", ".", "Time", "=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "depth", ".", "Asks", "=", "r", ".", "Result", ".", "Sell", ".", "makePts", "(", ")", "\n", "depth", ".", "Bids", "=", "r", ".", "Result", ".", "Buy", ".", "makePts", "(", ")", "\n", "return", "depth", "\n", "}" ]
// Translate the Bittrex response to DepthData.
[ "Translate", "the", "Bittrex", "response", "to", "DepthData", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1099-L1112
train
decred/dcrdata
exchanges/exchanges.go
Refresh
func (bittrex *BittrexExchange) Refresh() { bittrex.LogRequest() priceResponse := new(BittrexPriceResponse) err := bittrex.fetch(bittrex.requests.price, priceResponse) if err != nil { bittrex.fail("Fetch", err) return } if !priceResponse.Success { bittrex.fail("Unsuccessful resquest", err) return } if len(priceResponse.Result) == 0 { bittrex.fail("No result", err) return } result := priceResponse.Result[0] if result.MarketName != bittrex.MarketName { bittrex.fail("Wrong market", fmt.Errorf("Expected market %s. Received %s", bittrex.MarketName, result.MarketName)) return } // Depth chart depthResponse := new(BittrexDepthResponse) err = bittrex.fetch(bittrex.requests.depth, depthResponse) if err != nil { log.Errorf("Failed to retrieve Bittrex depth chart data: %v", err) } depth := depthResponse.translate() // Check for expired candlesticks state := bittrex.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range bittrex.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", bittrex.token, bin) response := new(BittrexCandlestickResponse) err := bittrex.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from Bittrex for bin size %s: %v", string(bin), err) continue } if !response.Success { log.Errorf("DragonEx server error while fetching candlestick data. Message: %s", response.Message) } sticks := response.Result.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } bittrex.Update(&ExchangeState{ Price: result.Last, BaseVolume: result.BaseVolume, Volume: result.Volume, Change: result.Last - result.PrevDay, Depth: depth, Candlesticks: candlesticks, }) }
go
func (bittrex *BittrexExchange) Refresh() { bittrex.LogRequest() priceResponse := new(BittrexPriceResponse) err := bittrex.fetch(bittrex.requests.price, priceResponse) if err != nil { bittrex.fail("Fetch", err) return } if !priceResponse.Success { bittrex.fail("Unsuccessful resquest", err) return } if len(priceResponse.Result) == 0 { bittrex.fail("No result", err) return } result := priceResponse.Result[0] if result.MarketName != bittrex.MarketName { bittrex.fail("Wrong market", fmt.Errorf("Expected market %s. Received %s", bittrex.MarketName, result.MarketName)) return } // Depth chart depthResponse := new(BittrexDepthResponse) err = bittrex.fetch(bittrex.requests.depth, depthResponse) if err != nil { log.Errorf("Failed to retrieve Bittrex depth chart data: %v", err) } depth := depthResponse.translate() // Check for expired candlesticks state := bittrex.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range bittrex.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", bittrex.token, bin) response := new(BittrexCandlestickResponse) err := bittrex.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from Bittrex for bin size %s: %v", string(bin), err) continue } if !response.Success { log.Errorf("DragonEx server error while fetching candlestick data. Message: %s", response.Message) } sticks := response.Result.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } bittrex.Update(&ExchangeState{ Price: result.Last, BaseVolume: result.BaseVolume, Volume: result.Volume, Change: result.Last - result.PrevDay, Depth: depth, Candlesticks: candlesticks, }) }
[ "func", "(", "bittrex", "*", "BittrexExchange", ")", "Refresh", "(", ")", "{", "bittrex", ".", "LogRequest", "(", ")", "\n", "priceResponse", ":=", "new", "(", "BittrexPriceResponse", ")", "\n", "err", ":=", "bittrex", ".", "fetch", "(", "bittrex", ".", "requests", ".", "price", ",", "priceResponse", ")", "\n", "if", "err", "!=", "nil", "{", "bittrex", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "!", "priceResponse", ".", "Success", "{", "bittrex", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "priceResponse", ".", "Result", ")", "==", "0", "{", "bittrex", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "result", ":=", "priceResponse", ".", "Result", "[", "0", "]", "\n", "if", "result", ".", "MarketName", "!=", "bittrex", ".", "MarketName", "{", "bittrex", ".", "fail", "(", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "bittrex", ".", "MarketName", ",", "result", ".", "MarketName", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Depth chart", "depthResponse", ":=", "new", "(", "BittrexDepthResponse", ")", "\n", "err", "=", "bittrex", ".", "fetch", "(", "bittrex", ".", "requests", ".", "depth", ",", "depthResponse", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "depth", ":=", "depthResponse", ".", "translate", "(", ")", "\n\n", "// Check for expired candlesticks", "state", ":=", "bittrex", ".", "state", "(", ")", "\n", "candlesticks", ":=", "map", "[", "candlestickKey", "]", "Candlesticks", "{", "}", "\n", "for", "bin", ",", "req", ":=", "range", "bittrex", ".", "requests", ".", "candlesticks", "{", "oldSticks", ",", "found", ":=", "state", ".", "Candlesticks", "[", "bin", "]", "\n", "if", "!", "found", "||", "oldSticks", ".", "needsUpdate", "(", "bin", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "bittrex", ".", "token", ",", "bin", ")", "\n", "response", ":=", "new", "(", "BittrexCandlestickResponse", ")", "\n", "err", ":=", "bittrex", ".", "fetch", "(", "req", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "bin", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "response", ".", "Success", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "response", ".", "Message", ")", "\n", "}", "\n\n", "sticks", ":=", "response", ".", "Result", ".", "translate", "(", ")", "\n", "if", "!", "found", "||", "sticks", ".", "time", "(", ")", ".", "After", "(", "oldSticks", ".", "time", "(", ")", ")", "{", "candlesticks", "[", "bin", "]", "=", "sticks", "\n", "}", "\n", "}", "\n", "}", "\n\n", "bittrex", ".", "Update", "(", "&", "ExchangeState", "{", "Price", ":", "result", ".", "Last", ",", "BaseVolume", ":", "result", ".", "BaseVolume", ",", "Volume", ":", "result", ".", "Volume", ",", "Change", ":", "result", ".", "Last", "-", "result", ".", "PrevDay", ",", "Depth", ":", "depth", ",", "Candlesticks", ":", "candlesticks", ",", "}", ")", "\n", "}" ]
// Refresh retrieves and parses API data from Bittrex. // Bittrex provides timestamps in a string format that is not quite RFC 3339.
[ "Refresh", "retrieves", "and", "parses", "API", "data", "from", "Bittrex", ".", "Bittrex", "provides", "timestamps", "in", "a", "string", "format", "that", "is", "not", "quite", "RFC", "3339", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1159-L1221
train
decred/dcrdata
exchanges/exchanges.go
NewDragonEx
func NewDragonEx(client *http.Client, channels *BotChannels) (dragonex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, DragonExURLs.Price, nil) if err != nil { return } // Dragonex has separate endpoints for buy and sell, so the requests are // stored as fields of DragonExchange var depthSell, depthBuy *http.Request depthSell, err = http.NewRequest(http.MethodGet, fmt.Sprintf(DragonExURLs.Depth, "sell"), nil) if err != nil { return } depthBuy, err = http.NewRequest(http.MethodGet, fmt.Sprintf(DragonExURLs.Depth, "buy"), nil) if err != nil { return } for dur, url := range DragonExURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } dragonex = &DragonExchange{ CommonExchange: newCommonExchange(DragonEx, client, reqs, channels), SymbolID: 1520101, depthBuyRequest: depthBuy, depthSellRequest: depthSell, } return }
go
func NewDragonEx(client *http.Client, channels *BotChannels) (dragonex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, DragonExURLs.Price, nil) if err != nil { return } // Dragonex has separate endpoints for buy and sell, so the requests are // stored as fields of DragonExchange var depthSell, depthBuy *http.Request depthSell, err = http.NewRequest(http.MethodGet, fmt.Sprintf(DragonExURLs.Depth, "sell"), nil) if err != nil { return } depthBuy, err = http.NewRequest(http.MethodGet, fmt.Sprintf(DragonExURLs.Depth, "buy"), nil) if err != nil { return } for dur, url := range DragonExURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } dragonex = &DragonExchange{ CommonExchange: newCommonExchange(DragonEx, client, reqs, channels), SymbolID: 1520101, depthBuyRequest: depthBuy, depthSellRequest: depthSell, } return }
[ "func", "NewDragonEx", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "dragonex", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "DragonExURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Dragonex has separate endpoints for buy and sell, so the requests are", "// stored as fields of DragonExchange", "var", "depthSell", ",", "depthBuy", "*", "http", ".", "Request", "\n", "depthSell", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "fmt", ".", "Sprintf", "(", "DragonExURLs", ".", "Depth", ",", "\"", "\"", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "depthBuy", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "fmt", ".", "Sprintf", "(", "DragonExURLs", ".", "Depth", ",", "\"", "\"", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "dur", ",", "url", ":=", "range", "DragonExURLs", ".", "Candlesticks", "{", "reqs", ".", "candlesticks", "[", "dur", "]", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "dragonex", "=", "&", "DragonExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "DragonEx", ",", "client", ",", "reqs", ",", "channels", ")", ",", "SymbolID", ":", "1520101", ",", "depthBuyRequest", ":", "depthBuy", ",", "depthSellRequest", ":", "depthSell", ",", "}", "\n", "return", "\n", "}" ]
// NewDragonEx constructs a DragonExchange.
[ "NewDragonEx", "constructs", "a", "DragonExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1232-L1266
train
decred/dcrdata
exchanges/exchanges.go
NewHuobi
func NewHuobi(client *http.Client, channels *BotChannels) (huobi Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, HuobiURLs.Price, nil) if err != nil { return } reqs.price.Header.Add("Content-Type", "application/x-www-form-urlencoded") reqs.depth, err = http.NewRequest(http.MethodGet, HuobiURLs.Depth, nil) if err != nil { return } reqs.depth.Header.Add("Content-Type", "application/x-www-form-urlencoded") for dur, url := range HuobiURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } reqs.candlesticks[dur].Header.Add("Content-Type", "application/x-www-form-urlencoded") } return &HuobiExchange{ CommonExchange: newCommonExchange(Huobi, client, reqs, channels), Ok: "ok", }, nil }
go
func NewHuobi(client *http.Client, channels *BotChannels) (huobi Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, HuobiURLs.Price, nil) if err != nil { return } reqs.price.Header.Add("Content-Type", "application/x-www-form-urlencoded") reqs.depth, err = http.NewRequest(http.MethodGet, HuobiURLs.Depth, nil) if err != nil { return } reqs.depth.Header.Add("Content-Type", "application/x-www-form-urlencoded") for dur, url := range HuobiURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } reqs.candlesticks[dur].Header.Add("Content-Type", "application/x-www-form-urlencoded") } return &HuobiExchange{ CommonExchange: newCommonExchange(Huobi, client, reqs, channels), Ok: "ok", }, nil }
[ "func", "NewHuobi", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "huobi", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "HuobiURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "reqs", ".", "price", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "reqs", ".", "depth", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "HuobiURLs", ".", "Depth", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "reqs", ".", "depth", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "for", "dur", ",", "url", ":=", "range", "HuobiURLs", ".", "Candlesticks", "{", "reqs", ".", "candlesticks", "[", "dur", "]", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "reqs", ".", "candlesticks", "[", "dur", "]", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "HuobiExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Huobi", ",", "client", ",", "reqs", ",", "channels", ")", ",", "Ok", ":", "\"", "\"", ",", "}", ",", "nil", "\n", "}" ]
// NewHuobi constructs a HuobiExchange.
[ "NewHuobi", "constructs", "a", "HuobiExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1589-L1615
train
decred/dcrdata
exchanges/exchanges.go
Refresh
func (huobi *HuobiExchange) Refresh() { huobi.LogRequest() priceResponse := new(HuobiPriceResponse) err := huobi.fetch(huobi.requests.price, priceResponse) if err != nil { huobi.fail("Fetch", err) return } if priceResponse.Status != huobi.Ok { huobi.fail("Status not ok", fmt.Errorf("Expected status %s. Received %s", huobi.Ok, priceResponse.Status)) return } baseVolume := priceResponse.Tick.Vol // Depth data var depth *DepthData depthResponse := new(HuobiDepthResponse) err = huobi.fetch(huobi.requests.depth, depthResponse) if err != nil { log.Errorf("Huobi depth chart fetch error: %v", err) } else if depthResponse.Status != huobi.Ok { log.Errorf("Huobi server depth response error. status: %s", depthResponse.Status) } else { depth = &DepthData{ Time: depthResponse.Ts / 1000, Bids: depthResponse.Tick.Bids.translate(), Asks: depthResponse.Tick.Asks.translate(), } } // Candlestick data state := huobi.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range huobi.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", huobi.token, bin) response := new(HuobiCandlestickResponse) err := huobi.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from huobi for bin size %s: %v", string(bin), err) continue } if response.Status != huobi.Ok { log.Errorf("Huobi server error while fetching candlestick data. status: %s", response.Status) continue } sticks := response.Data.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } huobi.Update(&ExchangeState{ Price: priceResponse.Tick.Close, BaseVolume: baseVolume, Volume: baseVolume / priceResponse.Tick.Close, Change: priceResponse.Tick.Close - priceResponse.Tick.Open, Stamp: priceResponse.Ts / 1000, Depth: depth, Candlesticks: candlesticks, }) }
go
func (huobi *HuobiExchange) Refresh() { huobi.LogRequest() priceResponse := new(HuobiPriceResponse) err := huobi.fetch(huobi.requests.price, priceResponse) if err != nil { huobi.fail("Fetch", err) return } if priceResponse.Status != huobi.Ok { huobi.fail("Status not ok", fmt.Errorf("Expected status %s. Received %s", huobi.Ok, priceResponse.Status)) return } baseVolume := priceResponse.Tick.Vol // Depth data var depth *DepthData depthResponse := new(HuobiDepthResponse) err = huobi.fetch(huobi.requests.depth, depthResponse) if err != nil { log.Errorf("Huobi depth chart fetch error: %v", err) } else if depthResponse.Status != huobi.Ok { log.Errorf("Huobi server depth response error. status: %s", depthResponse.Status) } else { depth = &DepthData{ Time: depthResponse.Ts / 1000, Bids: depthResponse.Tick.Bids.translate(), Asks: depthResponse.Tick.Asks.translate(), } } // Candlestick data state := huobi.state() candlesticks := map[candlestickKey]Candlesticks{} for bin, req := range huobi.requests.candlesticks { oldSticks, found := state.Candlesticks[bin] if !found || oldSticks.needsUpdate(bin) { log.Tracef("Signalling candlestick update for %s, bin size %s", huobi.token, bin) response := new(HuobiCandlestickResponse) err := huobi.fetch(req, response) if err != nil { log.Errorf("Error retrieving candlestick data from huobi for bin size %s: %v", string(bin), err) continue } if response.Status != huobi.Ok { log.Errorf("Huobi server error while fetching candlestick data. status: %s", response.Status) continue } sticks := response.Data.translate() if !found || sticks.time().After(oldSticks.time()) { candlesticks[bin] = sticks } } } huobi.Update(&ExchangeState{ Price: priceResponse.Tick.Close, BaseVolume: baseVolume, Volume: baseVolume / priceResponse.Tick.Close, Change: priceResponse.Tick.Close - priceResponse.Tick.Open, Stamp: priceResponse.Ts / 1000, Depth: depth, Candlesticks: candlesticks, }) }
[ "func", "(", "huobi", "*", "HuobiExchange", ")", "Refresh", "(", ")", "{", "huobi", ".", "LogRequest", "(", ")", "\n", "priceResponse", ":=", "new", "(", "HuobiPriceResponse", ")", "\n", "err", ":=", "huobi", ".", "fetch", "(", "huobi", ".", "requests", ".", "price", ",", "priceResponse", ")", "\n", "if", "err", "!=", "nil", "{", "huobi", ".", "fail", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "priceResponse", ".", "Status", "!=", "huobi", ".", "Ok", "{", "huobi", ".", "fail", "(", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "huobi", ".", "Ok", ",", "priceResponse", ".", "Status", ")", ")", "\n", "return", "\n", "}", "\n", "baseVolume", ":=", "priceResponse", ".", "Tick", ".", "Vol", "\n\n", "// Depth data", "var", "depth", "*", "DepthData", "\n", "depthResponse", ":=", "new", "(", "HuobiDepthResponse", ")", "\n", "err", "=", "huobi", ".", "fetch", "(", "huobi", ".", "requests", ".", "depth", ",", "depthResponse", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "if", "depthResponse", ".", "Status", "!=", "huobi", ".", "Ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "depthResponse", ".", "Status", ")", "\n", "}", "else", "{", "depth", "=", "&", "DepthData", "{", "Time", ":", "depthResponse", ".", "Ts", "/", "1000", ",", "Bids", ":", "depthResponse", ".", "Tick", ".", "Bids", ".", "translate", "(", ")", ",", "Asks", ":", "depthResponse", ".", "Tick", ".", "Asks", ".", "translate", "(", ")", ",", "}", "\n", "}", "\n\n", "// Candlestick data", "state", ":=", "huobi", ".", "state", "(", ")", "\n", "candlesticks", ":=", "map", "[", "candlestickKey", "]", "Candlesticks", "{", "}", "\n", "for", "bin", ",", "req", ":=", "range", "huobi", ".", "requests", ".", "candlesticks", "{", "oldSticks", ",", "found", ":=", "state", ".", "Candlesticks", "[", "bin", "]", "\n", "if", "!", "found", "||", "oldSticks", ".", "needsUpdate", "(", "bin", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "huobi", ".", "token", ",", "bin", ")", "\n", "response", ":=", "new", "(", "HuobiCandlestickResponse", ")", "\n", "err", ":=", "huobi", ".", "fetch", "(", "req", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "bin", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "response", ".", "Status", "!=", "huobi", ".", "Ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "response", ".", "Status", ")", "\n", "continue", "\n", "}", "\n\n", "sticks", ":=", "response", ".", "Data", ".", "translate", "(", ")", "\n", "if", "!", "found", "||", "sticks", ".", "time", "(", ")", ".", "After", "(", "oldSticks", ".", "time", "(", ")", ")", "{", "candlesticks", "[", "bin", "]", "=", "sticks", "\n", "}", "\n", "}", "\n", "}", "\n\n", "huobi", ".", "Update", "(", "&", "ExchangeState", "{", "Price", ":", "priceResponse", ".", "Tick", ".", "Close", ",", "BaseVolume", ":", "baseVolume", ",", "Volume", ":", "baseVolume", "/", "priceResponse", ".", "Tick", ".", "Close", ",", "Change", ":", "priceResponse", ".", "Tick", ".", "Close", "-", "priceResponse", ".", "Tick", ".", "Open", ",", "Stamp", ":", "priceResponse", ".", "Ts", "/", "1000", ",", "Depth", ":", "depth", ",", "Candlesticks", ":", "candlesticks", ",", "}", ")", "\n", "}" ]
// Refresh retrieves and parses API data from Huobi.
[ "Refresh", "retrieves", "and", "parses", "API", "data", "from", "Huobi", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1713-L1777
train
decred/dcrdata
exchanges/exchanges.go
NewPoloniex
func NewPoloniex(client *http.Client, channels *BotChannels) (poloniex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, PoloniexURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, PoloniexURLs.Depth, nil) if err != nil { return } for dur, url := range PoloniexURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } p := &PoloniexExchange{ CommonExchange: newCommonExchange(Poloniex, client, reqs, channels), CurrencyPair: "BTC_DCR", asks: make(poloniexOrders), buys: make(poloniexOrders), } go func() { <-channels.done if p.ws != nil { p.ws.Close() } }() poloniex = p return }
go
func NewPoloniex(client *http.Client, channels *BotChannels) (poloniex Exchange, err error) { reqs := newRequests() reqs.price, err = http.NewRequest(http.MethodGet, PoloniexURLs.Price, nil) if err != nil { return } reqs.depth, err = http.NewRequest(http.MethodGet, PoloniexURLs.Depth, nil) if err != nil { return } for dur, url := range PoloniexURLs.Candlesticks { reqs.candlesticks[dur], err = http.NewRequest(http.MethodGet, url, nil) if err != nil { return } } p := &PoloniexExchange{ CommonExchange: newCommonExchange(Poloniex, client, reqs, channels), CurrencyPair: "BTC_DCR", asks: make(poloniexOrders), buys: make(poloniexOrders), } go func() { <-channels.done if p.ws != nil { p.ws.Close() } }() poloniex = p return }
[ "func", "NewPoloniex", "(", "client", "*", "http", ".", "Client", ",", "channels", "*", "BotChannels", ")", "(", "poloniex", "Exchange", ",", "err", "error", ")", "{", "reqs", ":=", "newRequests", "(", ")", "\n", "reqs", ".", "price", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "PoloniexURLs", ".", "Price", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "reqs", ".", "depth", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "PoloniexURLs", ".", "Depth", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "dur", ",", "url", ":=", "range", "PoloniexURLs", ".", "Candlesticks", "{", "reqs", ".", "candlesticks", "[", "dur", "]", ",", "err", "=", "http", ".", "NewRequest", "(", "http", ".", "MethodGet", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "p", ":=", "&", "PoloniexExchange", "{", "CommonExchange", ":", "newCommonExchange", "(", "Poloniex", ",", "client", ",", "reqs", ",", "channels", ")", ",", "CurrencyPair", ":", "\"", "\"", ",", "asks", ":", "make", "(", "poloniexOrders", ")", ",", "buys", ":", "make", "(", "poloniexOrders", ")", ",", "}", "\n", "go", "func", "(", ")", "{", "<-", "channels", ".", "done", "\n", "if", "p", ".", "ws", "!=", "nil", "{", "p", ".", "ws", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "poloniex", "=", "p", "\n", "return", "\n", "}" ]
// NewPoloniex constructs a PoloniexExchange.
[ "NewPoloniex", "constructs", "a", "PoloniexExchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1799-L1832
train
decred/dcrdata
exchanges/exchanges.go
processWsOrderbook
func (poloniex *PoloniexExchange) processWsOrderbook(sequenceID int64, responseList []interface{}) { subList, ok := responseList[0].([]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse 0th element of poloniex response array")) return } if len(subList) < 2 { poloniex.setWsFail(fmt.Errorf("Unexpected sub-list length in poloniex websocket response: %d", len(subList))) return } d, ok := subList[1].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse response map from poloniex websocket response")) return } orderBook, ok := d["orderBook"].([]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse orderbook list from poloniex websocket response")) return } if len(orderBook) < 2 { poloniex.setWsFail(fmt.Errorf("Unexpected orderBook list length in poloniex websocket response: %d", len(subList))) return } asks, ok := orderBook[0].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse asks from poloniex orderbook")) return } buys, ok := orderBook[1].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse buys from poloniex orderbook")) return } poloniex.orderMtx.Lock() defer poloniex.orderMtx.Unlock() poloniex.orderSeq = sequenceID err := poloniex.parseOrderMap(asks, poloniex.asks) if err != nil { poloniex.setWsFail(err) return } err = poloniex.parseOrderMap(buys, poloniex.buys) if err != nil { poloniex.setWsFail(err) return } }
go
func (poloniex *PoloniexExchange) processWsOrderbook(sequenceID int64, responseList []interface{}) { subList, ok := responseList[0].([]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse 0th element of poloniex response array")) return } if len(subList) < 2 { poloniex.setWsFail(fmt.Errorf("Unexpected sub-list length in poloniex websocket response: %d", len(subList))) return } d, ok := subList[1].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse response map from poloniex websocket response")) return } orderBook, ok := d["orderBook"].([]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse orderbook list from poloniex websocket response")) return } if len(orderBook) < 2 { poloniex.setWsFail(fmt.Errorf("Unexpected orderBook list length in poloniex websocket response: %d", len(subList))) return } asks, ok := orderBook[0].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse asks from poloniex orderbook")) return } buys, ok := orderBook[1].(map[string]interface{}) if !ok { poloniex.setWsFail(fmt.Errorf("Failed to parse buys from poloniex orderbook")) return } poloniex.orderMtx.Lock() defer poloniex.orderMtx.Unlock() poloniex.orderSeq = sequenceID err := poloniex.parseOrderMap(asks, poloniex.asks) if err != nil { poloniex.setWsFail(err) return } err = poloniex.parseOrderMap(buys, poloniex.buys) if err != nil { poloniex.setWsFail(err) return } }
[ "func", "(", "poloniex", "*", "PoloniexExchange", ")", "processWsOrderbook", "(", "sequenceID", "int64", ",", "responseList", "[", "]", "interface", "{", "}", ")", "{", "subList", ",", "ok", ":=", "responseList", "[", "0", "]", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "subList", ")", "<", "2", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "subList", ")", ")", ")", "\n", "return", "\n", "}", "\n", "d", ",", "ok", ":=", "subList", "[", "1", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n", "orderBook", ",", "ok", ":=", "d", "[", "\"", "\"", "]", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "orderBook", ")", "<", "2", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "subList", ")", ")", ")", "\n", "return", "\n", "}", "\n", "asks", ",", "ok", ":=", "orderBook", "[", "0", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n\n", "buys", ",", "ok", ":=", "orderBook", "[", "1", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n\n", "poloniex", ".", "orderMtx", ".", "Lock", "(", ")", "\n", "defer", "poloniex", ".", "orderMtx", ".", "Unlock", "(", ")", "\n", "poloniex", ".", "orderSeq", "=", "sequenceID", "\n", "err", ":=", "poloniex", ".", "parseOrderMap", "(", "asks", ",", "poloniex", ".", "asks", ")", "\n", "if", "err", "!=", "nil", "{", "poloniex", ".", "setWsFail", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "poloniex", ".", "parseOrderMap", "(", "buys", ",", "poloniex", ".", "buys", ")", "\n", "if", "err", "!=", "nil", "{", "poloniex", ".", "setWsFail", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}" ]
// This initial websocket message is a full orderbook.
[ "This", "initial", "websocket", "message", "is", "a", "full", "orderbook", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L1994-L2044
train
decred/dcrdata
exchanges/exchanges.go
mergePoloniexDepthUpdates
func mergePoloniexDepthUpdates(target, source poloniexOrders) { for bin, pt := range source { if pt.volume == 0 { delete(source, bin) delete(target, bin) continue } target[bin] = pt } }
go
func mergePoloniexDepthUpdates(target, source poloniexOrders) { for bin, pt := range source { if pt.volume == 0 { delete(source, bin) delete(target, bin) continue } target[bin] = pt } }
[ "func", "mergePoloniexDepthUpdates", "(", "target", ",", "source", "poloniexOrders", ")", "{", "for", "bin", ",", "pt", ":=", "range", "source", "{", "if", "pt", ".", "volume", "==", "0", "{", "delete", "(", "source", ",", "bin", ")", "\n", "delete", "(", "target", ",", "bin", ")", "\n", "continue", "\n", "}", "\n", "target", "[", "bin", "]", "=", "pt", "\n", "}", "\n", "}" ]
// A helper for merging a source map into a target map. Poloniex order in the // source map with volume 0 will trigger a deletion from the target map.
[ "A", "helper", "for", "merging", "a", "source", "map", "into", "a", "target", "map", ".", "Poloniex", "order", "in", "the", "source", "map", "with", "volume", "0", "will", "trigger", "a", "deletion", "from", "the", "target", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2048-L2057
train
decred/dcrdata
exchanges/exchanges.go
accumulateOrders
func (poloniex *PoloniexExchange) accumulateOrders(sequenceID int64, asks, buys poloniexOrders) { poloniex.orderMtx.Lock() defer poloniex.orderMtx.Unlock() poloniex.orderSeq++ if sequenceID != poloniex.orderSeq { poloniex.setWsFail(fmt.Errorf("poloniex sequence id failure. expected %d, received %d", poloniex.orderSeq, sequenceID)) return } mergePoloniexDepthUpdates(poloniex.asks, asks) mergePoloniexDepthUpdates(poloniex.buys, buys) }
go
func (poloniex *PoloniexExchange) accumulateOrders(sequenceID int64, asks, buys poloniexOrders) { poloniex.orderMtx.Lock() defer poloniex.orderMtx.Unlock() poloniex.orderSeq++ if sequenceID != poloniex.orderSeq { poloniex.setWsFail(fmt.Errorf("poloniex sequence id failure. expected %d, received %d", poloniex.orderSeq, sequenceID)) return } mergePoloniexDepthUpdates(poloniex.asks, asks) mergePoloniexDepthUpdates(poloniex.buys, buys) }
[ "func", "(", "poloniex", "*", "PoloniexExchange", ")", "accumulateOrders", "(", "sequenceID", "int64", ",", "asks", ",", "buys", "poloniexOrders", ")", "{", "poloniex", ".", "orderMtx", ".", "Lock", "(", ")", "\n", "defer", "poloniex", ".", "orderMtx", ".", "Unlock", "(", ")", "\n", "poloniex", ".", "orderSeq", "++", "\n", "if", "sequenceID", "!=", "poloniex", ".", "orderSeq", "{", "poloniex", ".", "setWsFail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "poloniex", ".", "orderSeq", ",", "sequenceID", ")", ")", "\n", "return", "\n", "}", "\n", "mergePoloniexDepthUpdates", "(", "poloniex", ".", "asks", ",", "asks", ")", "\n", "mergePoloniexDepthUpdates", "(", "poloniex", ".", "buys", ",", "buys", ")", "\n", "}" ]
// Merge order updates under a write lock.
[ "Merge", "order", "updates", "under", "a", "write", "lock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2060-L2070
train
decred/dcrdata
exchanges/exchanges.go
firstCode
func firstCode(responseList []interface{}) string { firstElement, ok := responseList[0].([]interface{}) if !ok { log.Errorf("parse failure in poloniex websocket message") return "" } if len(firstElement) < 1 { log.Errorf("unexpected number of parameters in poloniex websocket message") return "" } updateType, ok := firstElement[0].(string) if !ok { log.Errorf("failed to type convert poloniex message update type") return "" } return updateType }
go
func firstCode(responseList []interface{}) string { firstElement, ok := responseList[0].([]interface{}) if !ok { log.Errorf("parse failure in poloniex websocket message") return "" } if len(firstElement) < 1 { log.Errorf("unexpected number of parameters in poloniex websocket message") return "" } updateType, ok := firstElement[0].(string) if !ok { log.Errorf("failed to type convert poloniex message update type") return "" } return updateType }
[ "func", "firstCode", "(", "responseList", "[", "]", "interface", "{", "}", ")", "string", "{", "firstElement", ",", "ok", ":=", "responseList", "[", "0", "]", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "firstElement", ")", "<", "1", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "updateType", ",", "ok", ":=", "firstElement", "[", "0", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "updateType", "\n", "}" ]
// Poloniex has a string code in the result array indicating what type of // message it is.
[ "Poloniex", "has", "a", "string", "code", "in", "the", "result", "array", "indicating", "what", "type", "of", "message", "it", "is", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2084-L2100
train
decred/dcrdata
exchanges/exchanges.go
processPoloniexOrderbookUpdate
func processPoloniexOrderbookUpdate(updateParams []interface{}) (*poloniexOrder, int, error) { floatDir, ok := updateParams[1].(float64) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update direction") } direction := int(floatDir) priceStr, ok := updateParams[2].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update price") } price, err := strconv.ParseFloat(priceStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update price to float: %v", err) } volStr, ok := updateParams[3].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update volume") } volume, err := strconv.ParseFloat(volStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update volume to float: %v", err) } return &poloniexOrder{ price: price, volume: volume, }, direction, nil }
go
func processPoloniexOrderbookUpdate(updateParams []interface{}) (*poloniexOrder, int, error) { floatDir, ok := updateParams[1].(float64) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update direction") } direction := int(floatDir) priceStr, ok := updateParams[2].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update price") } price, err := strconv.ParseFloat(priceStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update price to float: %v", err) } volStr, ok := updateParams[3].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update volume") } volume, err := strconv.ParseFloat(volStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update volume to float: %v", err) } return &poloniexOrder{ price: price, volume: volume, }, direction, nil }
[ "func", "processPoloniexOrderbookUpdate", "(", "updateParams", "[", "]", "interface", "{", "}", ")", "(", "*", "poloniexOrder", ",", "int", ",", "error", ")", "{", "floatDir", ",", "ok", ":=", "updateParams", "[", "1", "]", ".", "(", "float64", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "direction", ":=", "int", "(", "floatDir", ")", "\n", "priceStr", ",", "ok", ":=", "updateParams", "[", "2", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "price", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceStr", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "volStr", ",", "ok", ":=", "updateParams", "[", "3", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "volume", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "volStr", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "poloniexOrder", "{", "price", ":", "price", ",", "volume", ":", "volume", ",", "}", ",", "direction", ",", "nil", "\n", "}" ]
// For Poloniex message "o", an update to the orderbook.
[ "For", "Poloniex", "message", "o", "an", "update", "to", "the", "orderbook", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2103-L2129
train
decred/dcrdata
exchanges/exchanges.go
processTrade
func (poloniex *PoloniexExchange) processTrade(tradeParams []interface{}) (*poloniexOrder, int, error) { if len(tradeParams) != 6 { return nil, -1, fmt.Errorf("Not enough parameters in poloniex trade notification. given: %d", len(tradeParams)) } floatDir, ok := tradeParams[2].(float64) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update direction") } direction := (int(floatDir) + 1) % 2 priceStr, ok := tradeParams[3].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update price") } price, err := strconv.ParseFloat(priceStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update price to float: %v", err) } volStr, ok := tradeParams[4].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update volume") } volume, err := strconv.ParseFloat(volStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update volume to float: %v", err) } trade := &poloniexOrder{ price: price, volume: volume, } return trade, direction, nil }
go
func (poloniex *PoloniexExchange) processTrade(tradeParams []interface{}) (*poloniexOrder, int, error) { if len(tradeParams) != 6 { return nil, -1, fmt.Errorf("Not enough parameters in poloniex trade notification. given: %d", len(tradeParams)) } floatDir, ok := tradeParams[2].(float64) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update direction") } direction := (int(floatDir) + 1) % 2 priceStr, ok := tradeParams[3].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update price") } price, err := strconv.ParseFloat(priceStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update price to float: %v", err) } volStr, ok := tradeParams[4].(string) if !ok { return nil, -1, fmt.Errorf("failed to type convert poloniex orderbook update volume") } volume, err := strconv.ParseFloat(volStr, 64) if err != nil { return nil, -1, fmt.Errorf("failed to convert poloniex orderbook update volume to float: %v", err) } trade := &poloniexOrder{ price: price, volume: volume, } return trade, direction, nil }
[ "func", "(", "poloniex", "*", "PoloniexExchange", ")", "processTrade", "(", "tradeParams", "[", "]", "interface", "{", "}", ")", "(", "*", "poloniexOrder", ",", "int", ",", "error", ")", "{", "if", "len", "(", "tradeParams", ")", "!=", "6", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tradeParams", ")", ")", "\n", "}", "\n", "floatDir", ",", "ok", ":=", "tradeParams", "[", "2", "]", ".", "(", "float64", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "direction", ":=", "(", "int", "(", "floatDir", ")", "+", "1", ")", "%", "2", "\n", "priceStr", ",", "ok", ":=", "tradeParams", "[", "3", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "price", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "priceStr", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "volStr", ",", "ok", ":=", "tradeParams", "[", "4", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "volume", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "volStr", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "trade", ":=", "&", "poloniexOrder", "{", "price", ":", "price", ",", "volume", ":", "volume", ",", "}", "\n", "return", "trade", ",", "direction", ",", "nil", "\n", "}" ]
// For Poloniex message "t", a trade. This seems to be used rarely and // sporadically, but it is used. For the BTC_DCR endpoint, almost all updates // are of the "o" type, an orderbook update. The docs are unclear about whether a trade updates the // order book, but testing seems to indicate that a "t" message is for trades // that occur off of the orderbook.
[ "For", "Poloniex", "message", "t", "a", "trade", ".", "This", "seems", "to", "be", "used", "rarely", "and", "sporadically", "but", "it", "is", "used", ".", "For", "the", "BTC_DCR", "endpoint", "almost", "all", "updates", "are", "of", "the", "o", "type", "an", "orderbook", "update", ".", "The", "docs", "are", "unclear", "about", "whether", "a", "trade", "updates", "the", "order", "book", "but", "testing", "seems", "to", "indicate", "that", "a", "t", "message", "is", "for", "trades", "that", "occur", "off", "of", "the", "orderbook", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2136-L2166
train
decred/dcrdata
exchanges/exchanges.go
poloniexBinKeys
func poloniexBinKeys(book poloniexOrders) []int64 { keys := make([]int64, 0, len(book)) for k := range book { keys = append(keys, k) } return keys }
go
func poloniexBinKeys(book poloniexOrders) []int64 { keys := make([]int64, 0, len(book)) for k := range book { keys = append(keys, k) } return keys }
[ "func", "poloniexBinKeys", "(", "book", "poloniexOrders", ")", "[", "]", "int64", "{", "keys", ":=", "make", "(", "[", "]", "int64", ",", "0", ",", "len", "(", "book", ")", ")", "\n", "for", "k", ":=", "range", "book", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// Pull out the int64 bin keys from the map.
[ "Pull", "out", "the", "int64", "bin", "keys", "from", "the", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2280-L2286
train
decred/dcrdata
exchanges/exchanges.go
wsDepths
func (poloniex *PoloniexExchange) wsDepths() *DepthData { poloniex.orderMtx.RLock() defer poloniex.orderMtx.RUnlock() askKeys := poloniexBinKeys(poloniex.asks) sort.Slice(askKeys, func(i, j int) bool { return askKeys[i] < askKeys[j] }) buyKeys := poloniexBinKeys(poloniex.buys) sort.Slice(buyKeys, func(i, j int) bool { return buyKeys[i] > buyKeys[j] }) a := make([]DepthPoint, 0, len(askKeys)) for _, bin := range askKeys { pt := poloniex.asks[bin] a = append(a, DepthPoint{ Quantity: pt.volume, Price: pt.price, }) } b := make([]DepthPoint, 0, len(buyKeys)) for _, bin := range buyKeys { pt := poloniex.buys[bin] b = append(b, DepthPoint{ Quantity: pt.volume, Price: pt.price, }) } return &DepthData{ Time: time.Now().Unix(), Asks: a, Bids: b, } }
go
func (poloniex *PoloniexExchange) wsDepths() *DepthData { poloniex.orderMtx.RLock() defer poloniex.orderMtx.RUnlock() askKeys := poloniexBinKeys(poloniex.asks) sort.Slice(askKeys, func(i, j int) bool { return askKeys[i] < askKeys[j] }) buyKeys := poloniexBinKeys(poloniex.buys) sort.Slice(buyKeys, func(i, j int) bool { return buyKeys[i] > buyKeys[j] }) a := make([]DepthPoint, 0, len(askKeys)) for _, bin := range askKeys { pt := poloniex.asks[bin] a = append(a, DepthPoint{ Quantity: pt.volume, Price: pt.price, }) } b := make([]DepthPoint, 0, len(buyKeys)) for _, bin := range buyKeys { pt := poloniex.buys[bin] b = append(b, DepthPoint{ Quantity: pt.volume, Price: pt.price, }) } return &DepthData{ Time: time.Now().Unix(), Asks: a, Bids: b, } }
[ "func", "(", "poloniex", "*", "PoloniexExchange", ")", "wsDepths", "(", ")", "*", "DepthData", "{", "poloniex", ".", "orderMtx", ".", "RLock", "(", ")", "\n", "defer", "poloniex", ".", "orderMtx", ".", "RUnlock", "(", ")", "\n", "askKeys", ":=", "poloniexBinKeys", "(", "poloniex", ".", "asks", ")", "\n", "sort", ".", "Slice", "(", "askKeys", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "askKeys", "[", "i", "]", "<", "askKeys", "[", "j", "]", "\n", "}", ")", "\n", "buyKeys", ":=", "poloniexBinKeys", "(", "poloniex", ".", "buys", ")", "\n", "sort", ".", "Slice", "(", "buyKeys", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "buyKeys", "[", "i", "]", ">", "buyKeys", "[", "j", "]", "\n", "}", ")", "\n", "a", ":=", "make", "(", "[", "]", "DepthPoint", ",", "0", ",", "len", "(", "askKeys", ")", ")", "\n", "for", "_", ",", "bin", ":=", "range", "askKeys", "{", "pt", ":=", "poloniex", ".", "asks", "[", "bin", "]", "\n", "a", "=", "append", "(", "a", ",", "DepthPoint", "{", "Quantity", ":", "pt", ".", "volume", ",", "Price", ":", "pt", ".", "price", ",", "}", ")", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "DepthPoint", ",", "0", ",", "len", "(", "buyKeys", ")", ")", "\n", "for", "_", ",", "bin", ":=", "range", "buyKeys", "{", "pt", ":=", "poloniex", ".", "buys", "[", "bin", "]", "\n", "b", "=", "append", "(", "b", ",", "DepthPoint", "{", "Quantity", ":", "pt", ".", "volume", ",", "Price", ":", "pt", ".", "price", ",", "}", ")", "\n", "}", "\n", "return", "&", "DepthData", "{", "Time", ":", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "Asks", ":", "a", ",", "Bids", ":", "b", ",", "}", "\n", "}" ]
// Convert the intermediate orderbook to a DepthData.
[ "Convert", "the", "intermediate", "orderbook", "to", "a", "DepthData", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2289-L2321
train
decred/dcrdata
exchanges/exchanges.go
connectWs
func (poloniex *PoloniexExchange) connectWs() { poloniex.connectWebsocket(poloniex.processWsMessage, &socketConfig{ address: PoloniexURLs.Websocket, }) poloniex.wsSend(poloniexOrderbookSubscription) }
go
func (poloniex *PoloniexExchange) connectWs() { poloniex.connectWebsocket(poloniex.processWsMessage, &socketConfig{ address: PoloniexURLs.Websocket, }) poloniex.wsSend(poloniexOrderbookSubscription) }
[ "func", "(", "poloniex", "*", "PoloniexExchange", ")", "connectWs", "(", ")", "{", "poloniex", ".", "connectWebsocket", "(", "poloniex", ".", "processWsMessage", ",", "&", "socketConfig", "{", "address", ":", "PoloniexURLs", ".", "Websocket", ",", "}", ")", "\n", "poloniex", ".", "wsSend", "(", "poloniexOrderbookSubscription", ")", "\n", "}" ]
// Create a websocket connection and send the orderbook subscription.
[ "Create", "a", "websocket", "connection", "and", "send", "the", "orderbook", "subscription", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/exchanges.go#L2324-L2329
train
decred/dcrdata
db/cache/charts.go
ParseZoom
func ParseZoom(zoom string) ZoomLevel { switch ZoomLevel(zoom) { case BlockZoom: return BlockZoom case WindowZoom: return WindowZoom } return DefaultZoomLevel }
go
func ParseZoom(zoom string) ZoomLevel { switch ZoomLevel(zoom) { case BlockZoom: return BlockZoom case WindowZoom: return WindowZoom } return DefaultZoomLevel }
[ "func", "ParseZoom", "(", "zoom", "string", ")", "ZoomLevel", "{", "switch", "ZoomLevel", "(", "zoom", ")", "{", "case", "BlockZoom", ":", "return", "BlockZoom", "\n", "case", "WindowZoom", ":", "return", "WindowZoom", "\n", "}", "\n", "return", "DefaultZoomLevel", "\n", "}" ]
// ParseZoom will return the matching zoom level, else the default zoom.
[ "ParseZoom", "will", "return", "the", "matching", "zoom", "level", "else", "the", "default", "zoom", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L52-L60
train
decred/dcrdata
db/cache/charts.go
Snip
func (set *zoomSet) Snip(length int) { set.Height = set.Height.snip(length) set.Time = set.Time.snip(length) set.PoolSize = set.PoolSize.snip(length) set.PoolValue = set.PoolValue.snip(length) set.BlockSize = set.BlockSize.snip(length) set.TxCount = set.TxCount.snip(length) set.NewAtoms = set.NewAtoms.snip(length) set.Chainwork = set.Chainwork.snip(length) set.Fees = set.Fees.snip(length) }
go
func (set *zoomSet) Snip(length int) { set.Height = set.Height.snip(length) set.Time = set.Time.snip(length) set.PoolSize = set.PoolSize.snip(length) set.PoolValue = set.PoolValue.snip(length) set.BlockSize = set.BlockSize.snip(length) set.TxCount = set.TxCount.snip(length) set.NewAtoms = set.NewAtoms.snip(length) set.Chainwork = set.Chainwork.snip(length) set.Fees = set.Fees.snip(length) }
[ "func", "(", "set", "*", "zoomSet", ")", "Snip", "(", "length", "int", ")", "{", "set", ".", "Height", "=", "set", ".", "Height", ".", "snip", "(", "length", ")", "\n", "set", ".", "Time", "=", "set", ".", "Time", ".", "snip", "(", "length", ")", "\n", "set", ".", "PoolSize", "=", "set", ".", "PoolSize", ".", "snip", "(", "length", ")", "\n", "set", ".", "PoolValue", "=", "set", ".", "PoolValue", ".", "snip", "(", "length", ")", "\n", "set", ".", "BlockSize", "=", "set", ".", "BlockSize", ".", "snip", "(", "length", ")", "\n", "set", ".", "TxCount", "=", "set", ".", "TxCount", ".", "snip", "(", "length", ")", "\n", "set", ".", "NewAtoms", "=", "set", ".", "NewAtoms", ".", "snip", "(", "length", ")", "\n", "set", ".", "Chainwork", "=", "set", ".", "Chainwork", ".", "snip", "(", "length", ")", "\n", "set", ".", "Fees", "=", "set", ".", "Fees", ".", "snip", "(", "length", ")", "\n", "}" ]
// Snip truncates the zoomSet to a provided length.
[ "Snip", "truncates", "the", "zoomSet", "to", "a", "provided", "length", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L213-L223
train
decred/dcrdata
db/cache/charts.go
newBlockSet
func newBlockSet(size int) *zoomSet { return &zoomSet{ Time: newChartUints(size), PoolSize: newChartUints(size), PoolValue: newChartFloats(size), BlockSize: newChartUints(size), TxCount: newChartUints(size), NewAtoms: newChartUints(size), Chainwork: newChartUints(size), Fees: newChartUints(size), } }
go
func newBlockSet(size int) *zoomSet { return &zoomSet{ Time: newChartUints(size), PoolSize: newChartUints(size), PoolValue: newChartFloats(size), BlockSize: newChartUints(size), TxCount: newChartUints(size), NewAtoms: newChartUints(size), Chainwork: newChartUints(size), Fees: newChartUints(size), } }
[ "func", "newBlockSet", "(", "size", "int", ")", "*", "zoomSet", "{", "return", "&", "zoomSet", "{", "Time", ":", "newChartUints", "(", "size", ")", ",", "PoolSize", ":", "newChartUints", "(", "size", ")", ",", "PoolValue", ":", "newChartFloats", "(", "size", ")", ",", "BlockSize", ":", "newChartUints", "(", "size", ")", ",", "TxCount", ":", "newChartUints", "(", "size", ")", ",", "NewAtoms", ":", "newChartUints", "(", "size", ")", ",", "Chainwork", ":", "newChartUints", "(", "size", ")", ",", "Fees", ":", "newChartUints", "(", "size", ")", ",", "}", "\n", "}" ]
// Constructor for a sized zoomSet for blocks, which has has no Height slice // since the height is implicit for block-binned data.
[ "Constructor", "for", "a", "sized", "zoomSet", "for", "blocks", "which", "has", "has", "no", "Height", "slice", "since", "the", "height", "is", "implicit", "for", "block", "-", "binned", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L227-L238
train
decred/dcrdata
db/cache/charts.go
newDaySet
func newDaySet(size int) *zoomSet { set := newBlockSet(size) set.Height = newChartUints(size) return set }
go
func newDaySet(size int) *zoomSet { set := newBlockSet(size) set.Height = newChartUints(size) return set }
[ "func", "newDaySet", "(", "size", "int", ")", "*", "zoomSet", "{", "set", ":=", "newBlockSet", "(", "size", ")", "\n", "set", ".", "Height", "=", "newChartUints", "(", "size", ")", "\n", "return", "set", "\n", "}" ]
// Constructor for a sized zoomSet for day-binned data.
[ "Constructor", "for", "a", "sized", "zoomSet", "for", "day", "-", "binned", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L241-L245
train
decred/dcrdata
db/cache/charts.go
Snip
func (set *windowSet) Snip(length int) { set.Time = set.Time.snip(length) set.PowDiff = set.PowDiff.snip(length) set.TicketPrice = set.TicketPrice.snip(length) }
go
func (set *windowSet) Snip(length int) { set.Time = set.Time.snip(length) set.PowDiff = set.PowDiff.snip(length) set.TicketPrice = set.TicketPrice.snip(length) }
[ "func", "(", "set", "*", "windowSet", ")", "Snip", "(", "length", "int", ")", "{", "set", ".", "Time", "=", "set", ".", "Time", ".", "snip", "(", "length", ")", "\n", "set", ".", "PowDiff", "=", "set", ".", "PowDiff", ".", "snip", "(", "length", ")", "\n", "set", ".", "TicketPrice", "=", "set", ".", "TicketPrice", ".", "snip", "(", "length", ")", "\n", "}" ]
// Snip truncates the windowSet to a provided length.
[ "Snip", "truncates", "the", "windowSet", "to", "a", "provided", "length", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L257-L261
train
decred/dcrdata
db/cache/charts.go
newWindowSet
func newWindowSet(size int) *windowSet { return &windowSet{ Time: newChartUints(size), PowDiff: newChartFloats(size), TicketPrice: newChartUints(size), } }
go
func newWindowSet(size int) *windowSet { return &windowSet{ Time: newChartUints(size), PowDiff: newChartFloats(size), TicketPrice: newChartUints(size), } }
[ "func", "newWindowSet", "(", "size", "int", ")", "*", "windowSet", "{", "return", "&", "windowSet", "{", "Time", ":", "newChartUints", "(", "size", ")", ",", "PowDiff", ":", "newChartFloats", "(", "size", ")", ",", "TicketPrice", ":", "newChartUints", "(", "size", ")", ",", "}", "\n", "}" ]
// Constructor for a sized windowSet.
[ "Constructor", "for", "a", "sized", "windowSet", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L264-L270
train
decred/dcrdata
db/cache/charts.go
ValidateLengths
func ValidateLengths(lens ...lengther) (int, error) { lenLen := len(lens) if lenLen == 0 { return 0, nil } firstLen := lens[0].Length() shortest := firstLen for i, l := range lens[1:lenLen] { dLen := l.Length() if dLen < firstLen { log.Warnf("charts.ValidateLengths: dataset at index %d has mismatched length %d != %d", i+1, dLen, firstLen) if dLen < shortest { shortest = dLen } } } if shortest < firstLen { return shortest, fmt.Errorf("data length mismatch") } return firstLen, nil }
go
func ValidateLengths(lens ...lengther) (int, error) { lenLen := len(lens) if lenLen == 0 { return 0, nil } firstLen := lens[0].Length() shortest := firstLen for i, l := range lens[1:lenLen] { dLen := l.Length() if dLen < firstLen { log.Warnf("charts.ValidateLengths: dataset at index %d has mismatched length %d != %d", i+1, dLen, firstLen) if dLen < shortest { shortest = dLen } } } if shortest < firstLen { return shortest, fmt.Errorf("data length mismatch") } return firstLen, nil }
[ "func", "ValidateLengths", "(", "lens", "...", "lengther", ")", "(", "int", ",", "error", ")", "{", "lenLen", ":=", "len", "(", "lens", ")", "\n", "if", "lenLen", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "firstLen", ":=", "lens", "[", "0", "]", ".", "Length", "(", ")", "\n", "shortest", ":=", "firstLen", "\n", "for", "i", ",", "l", ":=", "range", "lens", "[", "1", ":", "lenLen", "]", "{", "dLen", ":=", "l", ".", "Length", "(", ")", "\n", "if", "dLen", "<", "firstLen", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "i", "+", "1", ",", "dLen", ",", "firstLen", ")", "\n", "if", "dLen", "<", "shortest", "{", "shortest", "=", "dLen", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "shortest", "<", "firstLen", "{", "return", "shortest", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "firstLen", ",", "nil", "\n", "}" ]
// Check that the length of all arguments is equal.
[ "Check", "that", "the", "length", "of", "all", "arguments", "is", "equal", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L331-L351
train
decred/dcrdata
db/cache/charts.go
midnight
func midnight(t uint64) (mid uint64) { if t > 0 { mid = t - t%aDay } return }
go
func midnight(t uint64) (mid uint64) { if t > 0 { mid = t - t%aDay } return }
[ "func", "midnight", "(", "t", "uint64", ")", "(", "mid", "uint64", ")", "{", "if", "t", ">", "0", "{", "mid", "=", "t", "-", "t", "%", "aDay", "\n", "}", "\n", "return", "\n", "}" ]
// Reduce the timestamp to the previous midnight.
[ "Reduce", "the", "timestamp", "to", "the", "previous", "midnight", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L354-L359
train
decred/dcrdata
db/cache/charts.go
ReorgHandler
func (charts *ChartData) ReorgHandler(wg *sync.WaitGroup, c chan *txhelpers.ReorgData) { defer func() { wg.Done() }() for { select { case data, ok := <-c: if !ok { return } commonAncestorHeight := uint64(data.NewChainHeight) - uint64(len(data.NewChain)) charts.mtx.Lock() defer charts.mtx.Unlock() charts.Blocks.Snip(int(commonAncestorHeight) + 1) // Snip the last two days daysLen := len(charts.Days.Time) daysLen -= 2 charts.Days.Snip(daysLen) // Drop the last window windowsLen := len(charts.Windows.Time) windowsLen-- charts.Windows.Snip(windowsLen) data.WG.Done() case <-charts.ctx.Done(): return } } }
go
func (charts *ChartData) ReorgHandler(wg *sync.WaitGroup, c chan *txhelpers.ReorgData) { defer func() { wg.Done() }() for { select { case data, ok := <-c: if !ok { return } commonAncestorHeight := uint64(data.NewChainHeight) - uint64(len(data.NewChain)) charts.mtx.Lock() defer charts.mtx.Unlock() charts.Blocks.Snip(int(commonAncestorHeight) + 1) // Snip the last two days daysLen := len(charts.Days.Time) daysLen -= 2 charts.Days.Snip(daysLen) // Drop the last window windowsLen := len(charts.Windows.Time) windowsLen-- charts.Windows.Snip(windowsLen) data.WG.Done() case <-charts.ctx.Done(): return } } }
[ "func", "(", "charts", "*", "ChartData", ")", "ReorgHandler", "(", "wg", "*", "sync", ".", "WaitGroup", ",", "c", "chan", "*", "txhelpers", ".", "ReorgData", ")", "{", "defer", "func", "(", ")", "{", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "for", "{", "select", "{", "case", "data", ",", "ok", ":=", "<-", "c", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n", "commonAncestorHeight", ":=", "uint64", "(", "data", ".", "NewChainHeight", ")", "-", "uint64", "(", "len", "(", "data", ".", "NewChain", ")", ")", "\n", "charts", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "charts", ".", "mtx", ".", "Unlock", "(", ")", "\n", "charts", ".", "Blocks", ".", "Snip", "(", "int", "(", "commonAncestorHeight", ")", "+", "1", ")", "\n", "// Snip the last two days", "daysLen", ":=", "len", "(", "charts", ".", "Days", ".", "Time", ")", "\n", "daysLen", "-=", "2", "\n", "charts", ".", "Days", ".", "Snip", "(", "daysLen", ")", "\n", "// Drop the last window", "windowsLen", ":=", "len", "(", "charts", ".", "Windows", ".", "Time", ")", "\n", "windowsLen", "--", "\n", "charts", ".", "Windows", ".", "Snip", "(", "windowsLen", ")", "\n", "data", ".", "WG", ".", "Done", "(", ")", "\n\n", "case", "<-", "charts", ".", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// ReorgHandler handles the charts cache data reorganization.
[ "ReorgHandler", "handles", "the", "charts", "cache", "data", "reorganization", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L458-L486
train
decred/dcrdata
db/cache/charts.go
Load
func (charts *ChartData) Load(cacheDumpPath string) { t := time.Now() if err := charts.readCacheFile(cacheDumpPath); err != nil { log.Debugf("Cache dump data loading failed: %v", err) } // Bring the charts up to date. charts.Update() log.Debugf("Completed the initial chart load in %d s", time.Since(t).Seconds()) }
go
func (charts *ChartData) Load(cacheDumpPath string) { t := time.Now() if err := charts.readCacheFile(cacheDumpPath); err != nil { log.Debugf("Cache dump data loading failed: %v", err) } // Bring the charts up to date. charts.Update() log.Debugf("Completed the initial chart load in %d s", time.Since(t).Seconds()) }
[ "func", "(", "charts", "*", "ChartData", ")", "Load", "(", "cacheDumpPath", "string", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", "\n\n", "if", "err", ":=", "charts", ".", "readCacheFile", "(", "cacheDumpPath", ")", ";", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Bring the charts up to date.", "charts", ".", "Update", "(", ")", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "time", ".", "Since", "(", "t", ")", ".", "Seconds", "(", ")", ")", "\n", "}" ]
// Load loads chart data from the gob file at the specified path and performs an // update.
[ "Load", "loads", "chart", "data", "from", "the", "gob", "file", "at", "the", "specified", "path", "and", "performs", "an", "update", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L569-L580
train
decred/dcrdata
db/cache/charts.go
Dump
func (charts *ChartData) Dump(dumpPath string) { err := charts.writeCacheFile(dumpPath) if err != nil { log.Errorf("ChartData.writeCacheFile failed: %v", err) } else { log.Debug("Dumping the charts cache data was successful") } }
go
func (charts *ChartData) Dump(dumpPath string) { err := charts.writeCacheFile(dumpPath) if err != nil { log.Errorf("ChartData.writeCacheFile failed: %v", err) } else { log.Debug("Dumping the charts cache data was successful") } }
[ "func", "(", "charts", "*", "ChartData", ")", "Dump", "(", "dumpPath", "string", ")", "{", "err", ":=", "charts", ".", "writeCacheFile", "(", "dumpPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Dump dumps a ChartGobject to a gob file at the given path.
[ "Dump", "dumps", "a", "ChartGobject", "to", "a", "gob", "file", "at", "the", "given", "path", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L583-L590
train
decred/dcrdata
db/cache/charts.go
FeesTip
func (charts *ChartData) FeesTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.Fees)) - 1 }
go
func (charts *ChartData) FeesTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.Fees)) - 1 }
[ "func", "(", "charts", "*", "ChartData", ")", "FeesTip", "(", ")", "int32", "{", "charts", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "charts", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "int32", "(", "len", "(", "charts", ".", "Blocks", ".", "Fees", ")", ")", "-", "1", "\n", "}" ]
// FeesTip is the height of the Fees data.
[ "FeesTip", "is", "the", "height", "of", "the", "Fees", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L649-L653
train
decred/dcrdata
db/cache/charts.go
NewAtomsTip
func (charts *ChartData) NewAtomsTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.NewAtoms)) - 1 }
go
func (charts *ChartData) NewAtomsTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.NewAtoms)) - 1 }
[ "func", "(", "charts", "*", "ChartData", ")", "NewAtomsTip", "(", ")", "int32", "{", "charts", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "charts", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "int32", "(", "len", "(", "charts", ".", "Blocks", ".", "NewAtoms", ")", ")", "-", "1", "\n", "}" ]
// NewAtomsTip is the height of the NewAtoms data.
[ "NewAtomsTip", "is", "the", "height", "of", "the", "NewAtoms", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L656-L660
train
decred/dcrdata
db/cache/charts.go
TicketPriceTip
func (charts *ChartData) TicketPriceTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Windows.TicketPrice))*charts.DiffInterval - 1 }
go
func (charts *ChartData) TicketPriceTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Windows.TicketPrice))*charts.DiffInterval - 1 }
[ "func", "(", "charts", "*", "ChartData", ")", "TicketPriceTip", "(", ")", "int32", "{", "charts", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "charts", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "int32", "(", "len", "(", "charts", ".", "Windows", ".", "TicketPrice", ")", ")", "*", "charts", ".", "DiffInterval", "-", "1", "\n", "}" ]
// TicketPriceTip is the height of the TicketPrice data.
[ "TicketPriceTip", "is", "the", "height", "of", "the", "TicketPrice", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L663-L667
train
decred/dcrdata
db/cache/charts.go
PoolSizeTip
func (charts *ChartData) PoolSizeTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.PoolSize)) - 1 }
go
func (charts *ChartData) PoolSizeTip() int32 { charts.mtx.RLock() defer charts.mtx.RUnlock() return int32(len(charts.Blocks.PoolSize)) - 1 }
[ "func", "(", "charts", "*", "ChartData", ")", "PoolSizeTip", "(", ")", "int32", "{", "charts", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "charts", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "int32", "(", "len", "(", "charts", ".", "Blocks", ".", "PoolSize", ")", ")", "-", "1", "\n", "}" ]
// PoolSizeTip is the height of the PoolSize data.
[ "PoolSizeTip", "is", "the", "height", "of", "the", "PoolSize", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L670-L674
train
decred/dcrdata
db/cache/charts.go
NewChartData
func NewChartData(height uint32, genesis time.Time, chainParams *chaincfg.Params, ctx context.Context) *ChartData { // Start datasets at 25% larger than height. This matches golangs default // capacity size increase for slice lengths > 1024 // https://github.com/golang/go/blob/87e48c5afdcf5e01bb2b7f51b7643e8901f4b7f9/src/runtime/slice.go#L100-L112 size := int(height * 5 / 4) days := int(int64(time.Since(genesis)/time.Hour/24)) * 5 / 4 windows := int(int64(height)/chainParams.StakeDiffWindowSize+1) * 5 / 4 return &ChartData{ ctx: ctx, genesis: uint64(genesis.Unix()), DiffInterval: int32(chainParams.StakeDiffWindowSize), Blocks: newBlockSet(size), Windows: newWindowSet(windows), Days: newDaySet(days), cache: make(map[string]*cachedChart), updaters: make([]ChartUpdater, 0), } }
go
func NewChartData(height uint32, genesis time.Time, chainParams *chaincfg.Params, ctx context.Context) *ChartData { // Start datasets at 25% larger than height. This matches golangs default // capacity size increase for slice lengths > 1024 // https://github.com/golang/go/blob/87e48c5afdcf5e01bb2b7f51b7643e8901f4b7f9/src/runtime/slice.go#L100-L112 size := int(height * 5 / 4) days := int(int64(time.Since(genesis)/time.Hour/24)) * 5 / 4 windows := int(int64(height)/chainParams.StakeDiffWindowSize+1) * 5 / 4 return &ChartData{ ctx: ctx, genesis: uint64(genesis.Unix()), DiffInterval: int32(chainParams.StakeDiffWindowSize), Blocks: newBlockSet(size), Windows: newWindowSet(windows), Days: newDaySet(days), cache: make(map[string]*cachedChart), updaters: make([]ChartUpdater, 0), } }
[ "func", "NewChartData", "(", "height", "uint32", ",", "genesis", "time", ".", "Time", ",", "chainParams", "*", "chaincfg", ".", "Params", ",", "ctx", "context", ".", "Context", ")", "*", "ChartData", "{", "// Start datasets at 25% larger than height. This matches golangs default", "// capacity size increase for slice lengths > 1024", "// https://github.com/golang/go/blob/87e48c5afdcf5e01bb2b7f51b7643e8901f4b7f9/src/runtime/slice.go#L100-L112", "size", ":=", "int", "(", "height", "*", "5", "/", "4", ")", "\n", "days", ":=", "int", "(", "int64", "(", "time", ".", "Since", "(", "genesis", ")", "/", "time", ".", "Hour", "/", "24", ")", ")", "*", "5", "/", "4", "\n", "windows", ":=", "int", "(", "int64", "(", "height", ")", "/", "chainParams", ".", "StakeDiffWindowSize", "+", "1", ")", "*", "5", "/", "4", "\n", "return", "&", "ChartData", "{", "ctx", ":", "ctx", ",", "genesis", ":", "uint64", "(", "genesis", ".", "Unix", "(", ")", ")", ",", "DiffInterval", ":", "int32", "(", "chainParams", ".", "StakeDiffWindowSize", ")", ",", "Blocks", ":", "newBlockSet", "(", "size", ")", ",", "Windows", ":", "newWindowSet", "(", "windows", ")", ",", "Days", ":", "newDaySet", "(", "days", ")", ",", "cache", ":", "make", "(", "map", "[", "string", "]", "*", "cachedChart", ")", ",", "updaters", ":", "make", "(", "[", "]", "ChartUpdater", ",", "0", ")", ",", "}", "\n", "}" ]
// NewChartData constructs a new ChartData.
[ "NewChartData", "constructs", "a", "new", "ChartData", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L712-L729
train
decred/dcrdata
db/cache/charts.go
getCache
func (charts *ChartData) getCache(chartID string, zoom ZoomLevel) (data *cachedChart, found bool, cacheID uint64) { // Ignore zero length since bestHeight would just be set to zero anyway. ck := cacheKey(chartID, zoom) charts.cacheMtx.RLock() defer charts.cacheMtx.RUnlock() cacheID = charts.cacheID(zoom) data, found = charts.cache[ck] return }
go
func (charts *ChartData) getCache(chartID string, zoom ZoomLevel) (data *cachedChart, found bool, cacheID uint64) { // Ignore zero length since bestHeight would just be set to zero anyway. ck := cacheKey(chartID, zoom) charts.cacheMtx.RLock() defer charts.cacheMtx.RUnlock() cacheID = charts.cacheID(zoom) data, found = charts.cache[ck] return }
[ "func", "(", "charts", "*", "ChartData", ")", "getCache", "(", "chartID", "string", ",", "zoom", "ZoomLevel", ")", "(", "data", "*", "cachedChart", ",", "found", "bool", ",", "cacheID", "uint64", ")", "{", "// Ignore zero length since bestHeight would just be set to zero anyway.", "ck", ":=", "cacheKey", "(", "chartID", ",", "zoom", ")", "\n", "charts", ".", "cacheMtx", ".", "RLock", "(", ")", "\n", "defer", "charts", ".", "cacheMtx", ".", "RUnlock", "(", ")", "\n", "cacheID", "=", "charts", ".", "cacheID", "(", "zoom", ")", "\n", "data", ",", "found", "=", "charts", ".", "cache", "[", "ck", "]", "\n", "return", "\n", "}" ]
// Grab the cached data, if it exists. The cacheID is returned as a convenience.
[ "Grab", "the", "cached", "data", "if", "it", "exists", ".", "The", "cacheID", "is", "returned", "as", "a", "convenience", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L751-L759
train
decred/dcrdata
db/cache/charts.go
cacheChart
func (charts *ChartData) cacheChart(chartID string, zoom ZoomLevel, data []byte) { ck := cacheKey(chartID, zoom) charts.cacheMtx.Lock() defer charts.cacheMtx.Unlock() // Using the current best cacheID. This leaves open the small possibility that // the cacheID is wrong, if the cacheID has been updated between the // ChartMaker and here. This would just cause a one block delay. charts.cache[ck] = &cachedChart{ cacheID: charts.cacheID(zoom), data: data, } }
go
func (charts *ChartData) cacheChart(chartID string, zoom ZoomLevel, data []byte) { ck := cacheKey(chartID, zoom) charts.cacheMtx.Lock() defer charts.cacheMtx.Unlock() // Using the current best cacheID. This leaves open the small possibility that // the cacheID is wrong, if the cacheID has been updated between the // ChartMaker and here. This would just cause a one block delay. charts.cache[ck] = &cachedChart{ cacheID: charts.cacheID(zoom), data: data, } }
[ "func", "(", "charts", "*", "ChartData", ")", "cacheChart", "(", "chartID", "string", ",", "zoom", "ZoomLevel", ",", "data", "[", "]", "byte", ")", "{", "ck", ":=", "cacheKey", "(", "chartID", ",", "zoom", ")", "\n", "charts", ".", "cacheMtx", ".", "Lock", "(", ")", "\n", "defer", "charts", ".", "cacheMtx", ".", "Unlock", "(", ")", "\n", "// Using the current best cacheID. This leaves open the small possibility that", "// the cacheID is wrong, if the cacheID has been updated between the", "// ChartMaker and here. This would just cause a one block delay.", "charts", ".", "cache", "[", "ck", "]", "=", "&", "cachedChart", "{", "cacheID", ":", "charts", ".", "cacheID", "(", "zoom", ")", ",", "data", ":", "data", ",", "}", "\n", "}" ]
// Store the chart associated with the provided type and ZoomLevel.
[ "Store", "the", "chart", "associated", "with", "the", "provided", "type", "and", "ZoomLevel", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L762-L773
train
decred/dcrdata
db/cache/charts.go
Chart
func (charts *ChartData) Chart(chartID, zoomString string) ([]byte, error) { zoom := ParseZoom(zoomString) cache, found, cacheID := charts.getCache(chartID, zoom) if found && cache.cacheID == cacheID { return cache.data, nil } maker, hasMaker := chartMakers[chartID] if !hasMaker { return nil, UnknownChartErr } // Do the locking here, rather than in encodeXY, so that the helper functions // (accumulate, btw) are run under lock. charts.mtx.RLock() data, err := maker(charts, zoom) charts.mtx.RUnlock() if err != nil { return nil, err } charts.cacheChart(chartID, zoom, data) return data, nil }
go
func (charts *ChartData) Chart(chartID, zoomString string) ([]byte, error) { zoom := ParseZoom(zoomString) cache, found, cacheID := charts.getCache(chartID, zoom) if found && cache.cacheID == cacheID { return cache.data, nil } maker, hasMaker := chartMakers[chartID] if !hasMaker { return nil, UnknownChartErr } // Do the locking here, rather than in encodeXY, so that the helper functions // (accumulate, btw) are run under lock. charts.mtx.RLock() data, err := maker(charts, zoom) charts.mtx.RUnlock() if err != nil { return nil, err } charts.cacheChart(chartID, zoom, data) return data, nil }
[ "func", "(", "charts", "*", "ChartData", ")", "Chart", "(", "chartID", ",", "zoomString", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "zoom", ":=", "ParseZoom", "(", "zoomString", ")", "\n", "cache", ",", "found", ",", "cacheID", ":=", "charts", ".", "getCache", "(", "chartID", ",", "zoom", ")", "\n", "if", "found", "&&", "cache", ".", "cacheID", "==", "cacheID", "{", "return", "cache", ".", "data", ",", "nil", "\n", "}", "\n", "maker", ",", "hasMaker", ":=", "chartMakers", "[", "chartID", "]", "\n", "if", "!", "hasMaker", "{", "return", "nil", ",", "UnknownChartErr", "\n", "}", "\n", "// Do the locking here, rather than in encodeXY, so that the helper functions", "// (accumulate, btw) are run under lock.", "charts", ".", "mtx", ".", "RLock", "(", ")", "\n", "data", ",", "err", ":=", "maker", "(", "charts", ",", "zoom", ")", "\n", "charts", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "charts", ".", "cacheChart", "(", "chartID", ",", "zoom", ",", "data", ")", "\n", "return", "data", ",", "nil", "\n", "}" ]
// Chart will return a JSON-encoded chartResponse of the provided type // and ZoomLevel.
[ "Chart", "will", "return", "a", "JSON", "-", "encoded", "chartResponse", "of", "the", "provided", "type", "and", "ZoomLevel", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L796-L816
train
decred/dcrdata
db/cache/charts.go
encode
func (charts *ChartData) encode(sets ...lengther) ([]byte, error) { if len(sets) == 0 { return nil, fmt.Errorf("encode called without arguments") } smaller := sets[0].Length() for _, x := range sets { l := x.Length() if l < smaller { smaller = l } } response := make(chartResponse) for i := range sets { rk := responseKeys[i%len(responseKeys)] // If the length of the responseKeys array has been exceeded, add a integer // suffix to the response key. The key progression is x, y, z, x1, y1, z1, // x2, ... if i >= len(responseKeys) { rk += strconv.Itoa(i / len(responseKeys)) } response[rk] = sets[i].Truncate(smaller) } return json.Marshal(response) }
go
func (charts *ChartData) encode(sets ...lengther) ([]byte, error) { if len(sets) == 0 { return nil, fmt.Errorf("encode called without arguments") } smaller := sets[0].Length() for _, x := range sets { l := x.Length() if l < smaller { smaller = l } } response := make(chartResponse) for i := range sets { rk := responseKeys[i%len(responseKeys)] // If the length of the responseKeys array has been exceeded, add a integer // suffix to the response key. The key progression is x, y, z, x1, y1, z1, // x2, ... if i >= len(responseKeys) { rk += strconv.Itoa(i / len(responseKeys)) } response[rk] = sets[i].Truncate(smaller) } return json.Marshal(response) }
[ "func", "(", "charts", "*", "ChartData", ")", "encode", "(", "sets", "...", "lengther", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "sets", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "smaller", ":=", "sets", "[", "0", "]", ".", "Length", "(", ")", "\n", "for", "_", ",", "x", ":=", "range", "sets", "{", "l", ":=", "x", ".", "Length", "(", ")", "\n", "if", "l", "<", "smaller", "{", "smaller", "=", "l", "\n", "}", "\n", "}", "\n", "response", ":=", "make", "(", "chartResponse", ")", "\n", "for", "i", ":=", "range", "sets", "{", "rk", ":=", "responseKeys", "[", "i", "%", "len", "(", "responseKeys", ")", "]", "\n", "// If the length of the responseKeys array has been exceeded, add a integer", "// suffix to the response key. The key progression is x, y, z, x1, y1, z1,", "// x2, ...", "if", "i", ">=", "len", "(", "responseKeys", ")", "{", "rk", "+=", "strconv", ".", "Itoa", "(", "i", "/", "len", "(", "responseKeys", ")", ")", "\n", "}", "\n", "response", "[", "rk", "]", "=", "sets", "[", "i", "]", ".", "Truncate", "(", "smaller", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "response", ")", "\n", "}" ]
// Encode the slices. The set lengths are truncated to the smallest of the // arguments.
[ "Encode", "the", "slices", ".", "The", "set", "lengths", "are", "truncated", "to", "the", "smallest", "of", "the", "arguments", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L823-L846
train
decred/dcrdata
db/cache/charts.go
accumulate
func accumulate(data ChartUints) ChartUints { d := make(ChartUints, 0, len(data)) var accumulator uint64 for _, v := range data { accumulator += v d = append(d, accumulator) } return d }
go
func accumulate(data ChartUints) ChartUints { d := make(ChartUints, 0, len(data)) var accumulator uint64 for _, v := range data { accumulator += v d = append(d, accumulator) } return d }
[ "func", "accumulate", "(", "data", "ChartUints", ")", "ChartUints", "{", "d", ":=", "make", "(", "ChartUints", ",", "0", ",", "len", "(", "data", ")", ")", "\n", "var", "accumulator", "uint64", "\n", "for", "_", ",", "v", ":=", "range", "data", "{", "accumulator", "+=", "v", "\n", "d", "=", "append", "(", "d", ",", "accumulator", ")", "\n", "}", "\n", "return", "d", "\n", "}" ]
// Each point is translated to the sum of all points before and itself.
[ "Each", "point", "is", "translated", "to", "the", "sum", "of", "all", "points", "before", "and", "itself", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L849-L857
train
decred/dcrdata
db/cache/charts.go
btw
func btw(data ChartUints) ChartUints { d := make(ChartUints, 0, len(data)) dataLen := len(data) if dataLen == 0 { return d } d = append(d, 0) last := data[0] for _, v := range data[1:] { d = append(d, v-last) last = v } return d }
go
func btw(data ChartUints) ChartUints { d := make(ChartUints, 0, len(data)) dataLen := len(data) if dataLen == 0 { return d } d = append(d, 0) last := data[0] for _, v := range data[1:] { d = append(d, v-last) last = v } return d }
[ "func", "btw", "(", "data", "ChartUints", ")", "ChartUints", "{", "d", ":=", "make", "(", "ChartUints", ",", "0", ",", "len", "(", "data", ")", ")", "\n", "dataLen", ":=", "len", "(", "data", ")", "\n", "if", "dataLen", "==", "0", "{", "return", "d", "\n", "}", "\n", "d", "=", "append", "(", "d", ",", "0", ")", "\n", "last", ":=", "data", "[", "0", "]", "\n", "for", "_", ",", "v", ":=", "range", "data", "[", "1", ":", "]", "{", "d", "=", "append", "(", "d", ",", "v", "-", "last", ")", "\n", "last", "=", "v", "\n", "}", "\n", "return", "d", "\n", "}" ]
// Translate the uints to a slice of the differences between each. The provided // data is assumed to be monotonically increasing. The first element is always // 0 to keep the data length unchanged.
[ "Translate", "the", "uints", "to", "a", "slice", "of", "the", "differences", "between", "each", ".", "The", "provided", "data", "is", "assumed", "to", "be", "monotonically", "increasing", ".", "The", "first", "element", "is", "always", "0", "to", "keep", "the", "data", "length", "unchanged", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L862-L875
train
decred/dcrdata
db/cache/charts.go
hashrate
func hashrate(time, chainwork ChartUints) (ChartUints, ChartUints) { hrLen := len(chainwork) - HashrateAvgLength if hrLen <= 0 { return newChartUints(0), newChartUints(0) } t := make(ChartUints, 0, hrLen) y := make(ChartUints, 0, hrLen) var rotator [HashrateAvgLength]uint64 for i, work := range chainwork { idx := i % HashrateAvgLength rotator[idx] = work if i >= HashrateAvgLength { lastWork := rotator[(idx+1)%HashrateAvgLength] lastTime := time[i-HashrateAvgLength] thisTime := time[i] // 1e6: exahash -> terahash/s t = append(t, thisTime) y = append(y, (work-lastWork)*1e6/(thisTime-lastTime)) } } return t, y }
go
func hashrate(time, chainwork ChartUints) (ChartUints, ChartUints) { hrLen := len(chainwork) - HashrateAvgLength if hrLen <= 0 { return newChartUints(0), newChartUints(0) } t := make(ChartUints, 0, hrLen) y := make(ChartUints, 0, hrLen) var rotator [HashrateAvgLength]uint64 for i, work := range chainwork { idx := i % HashrateAvgLength rotator[idx] = work if i >= HashrateAvgLength { lastWork := rotator[(idx+1)%HashrateAvgLength] lastTime := time[i-HashrateAvgLength] thisTime := time[i] // 1e6: exahash -> terahash/s t = append(t, thisTime) y = append(y, (work-lastWork)*1e6/(thisTime-lastTime)) } } return t, y }
[ "func", "hashrate", "(", "time", ",", "chainwork", "ChartUints", ")", "(", "ChartUints", ",", "ChartUints", ")", "{", "hrLen", ":=", "len", "(", "chainwork", ")", "-", "HashrateAvgLength", "\n", "if", "hrLen", "<=", "0", "{", "return", "newChartUints", "(", "0", ")", ",", "newChartUints", "(", "0", ")", "\n", "}", "\n", "t", ":=", "make", "(", "ChartUints", ",", "0", ",", "hrLen", ")", "\n", "y", ":=", "make", "(", "ChartUints", ",", "0", ",", "hrLen", ")", "\n", "var", "rotator", "[", "HashrateAvgLength", "]", "uint64", "\n", "for", "i", ",", "work", ":=", "range", "chainwork", "{", "idx", ":=", "i", "%", "HashrateAvgLength", "\n", "rotator", "[", "idx", "]", "=", "work", "\n", "if", "i", ">=", "HashrateAvgLength", "{", "lastWork", ":=", "rotator", "[", "(", "idx", "+", "1", ")", "%", "HashrateAvgLength", "]", "\n", "lastTime", ":=", "time", "[", "i", "-", "HashrateAvgLength", "]", "\n", "thisTime", ":=", "time", "[", "i", "]", "\n", "// 1e6: exahash -> terahash/s", "t", "=", "append", "(", "t", ",", "thisTime", ")", "\n", "y", "=", "append", "(", "y", ",", "(", "work", "-", "lastWork", ")", "*", "1e6", "/", "(", "thisTime", "-", "lastTime", ")", ")", "\n", "}", "\n", "}", "\n", "return", "t", ",", "y", "\n", "}" ]
// hashrate converts the provided chainwork data to hashrate data. Since // hashrates are averaged over HashrateAvgLength blocks, the returned slice // is HashrateAvgLength shorter than the provided chainwork. A time slice is // required as well, and a truncated time slice with the same length as the // hashrate slice is returned.
[ "hashrate", "converts", "the", "provided", "chainwork", "data", "to", "hashrate", "data", ".", "Since", "hashrates", "are", "averaged", "over", "HashrateAvgLength", "blocks", "the", "returned", "slice", "is", "HashrateAvgLength", "shorter", "than", "the", "provided", "chainwork", ".", "A", "time", "slice", "is", "required", "as", "well", "and", "a", "truncated", "time", "slice", "with", "the", "same", "length", "as", "the", "hashrate", "slice", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/charts.go#L932-L953
train
decred/dcrdata
db/dcrpg/internal/addrstmts.go
formatGroupingQuery
func formatGroupingQuery(mainQuery, group, column string) string { if group == "all" { return fmt.Sprintf(mainQuery, column) } subQuery := fmt.Sprintf("date_trunc('%s', %s)", group, column) return fmt.Sprintf(mainQuery, subQuery) }
go
func formatGroupingQuery(mainQuery, group, column string) string { if group == "all" { return fmt.Sprintf(mainQuery, column) } subQuery := fmt.Sprintf("date_trunc('%s', %s)", group, column) return fmt.Sprintf(mainQuery, subQuery) }
[ "func", "formatGroupingQuery", "(", "mainQuery", ",", "group", ",", "column", "string", ")", "string", "{", "if", "group", "==", "\"", "\"", "{", "return", "fmt", ".", "Sprintf", "(", "mainQuery", ",", "column", ")", "\n", "}", "\n", "subQuery", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "group", ",", "column", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "mainQuery", ",", "subQuery", ")", "\n", "}" ]
// Since date_trunc function doesn't have an option to group by "all" grouping, // formatGroupingQuery removes the date_trunc from the sql query as its not applicable.
[ "Since", "date_trunc", "function", "doesn", "t", "have", "an", "option", "to", "group", "by", "all", "grouping", "formatGroupingQuery", "removes", "the", "date_trunc", "from", "the", "sql", "query", "as", "its", "not", "applicable", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/internal/addrstmts.go#L380-L386
train
decred/dcrdata
db/cache/addresscache.go
NewBlockID
func NewBlockID(hash *chainhash.Hash, height int64) *BlockID { return &BlockID{ Hash: *hash, Height: height, } }
go
func NewBlockID(hash *chainhash.Hash, height int64) *BlockID { return &BlockID{ Hash: *hash, Height: height, } }
[ "func", "NewBlockID", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int64", ")", "*", "BlockID", "{", "return", "&", "BlockID", "{", "Hash", ":", "*", "hash", ",", "Height", ":", "height", ",", "}", "\n", "}" ]
// NewBlockID constructs a new BlockID.
[ "NewBlockID", "constructs", "a", "new", "BlockID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L398-L403
train
decred/dcrdata
db/cache/addresscache.go
BlockHash
func (d *AddressCacheItem) BlockHash() chainhash.Hash { d.mtx.RLock() defer d.mtx.RUnlock() return d.hash }
go
func (d *AddressCacheItem) BlockHash() chainhash.Hash { d.mtx.RLock() defer d.mtx.RUnlock() return d.hash }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "BlockHash", "(", ")", "chainhash", ".", "Hash", "{", "d", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "hash", "\n", "}" ]
// BlockHash is a thread-safe accessor for the block hash.
[ "BlockHash", "is", "a", "thread", "-", "safe", "accessor", "for", "the", "block", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L411-L415
train
decred/dcrdata
db/cache/addresscache.go
BlockHeight
func (d *AddressCacheItem) BlockHeight() int64 { d.mtx.RLock() defer d.mtx.RUnlock() return d.height }
go
func (d *AddressCacheItem) BlockHeight() int64 { d.mtx.RLock() defer d.mtx.RUnlock() return d.height }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "BlockHeight", "(", ")", "int64", "{", "d", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "height", "\n", "}" ]
// BlockHeight is a thread-safe accessor for the block height.
[ "BlockHeight", "is", "a", "thread", "-", "safe", "accessor", "for", "the", "block", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L418-L422
train
decred/dcrdata
db/cache/addresscache.go
HistoryChart
func (d *AddressCacheItem) HistoryChart(addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping) (*dbtypes.ChartsData, *BlockID) { d.mtx.RLock() defer d.mtx.RUnlock() if int(chartGrouping) >= dbtypes.NumIntervals { log.Errorf("Invalid chart grouping: %v", chartGrouping) return nil, nil } var cd *dbtypes.ChartsData switch addrChart { case dbtypes.TxsType: cd = d.history.TypeByInterval[chartGrouping] case dbtypes.AmountFlow: cd = d.history.AmtFlowByInterval[chartGrouping] } if cd == nil { return nil, nil } return cd, d.blockID() }
go
func (d *AddressCacheItem) HistoryChart(addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping) (*dbtypes.ChartsData, *BlockID) { d.mtx.RLock() defer d.mtx.RUnlock() if int(chartGrouping) >= dbtypes.NumIntervals { log.Errorf("Invalid chart grouping: %v", chartGrouping) return nil, nil } var cd *dbtypes.ChartsData switch addrChart { case dbtypes.TxsType: cd = d.history.TypeByInterval[chartGrouping] case dbtypes.AmountFlow: cd = d.history.AmtFlowByInterval[chartGrouping] } if cd == nil { return nil, nil } return cd, d.blockID() }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "HistoryChart", "(", "addrChart", "dbtypes", ".", "HistoryChart", ",", "chartGrouping", "dbtypes", ".", "TimeBasedGrouping", ")", "(", "*", "dbtypes", ".", "ChartsData", ",", "*", "BlockID", ")", "{", "d", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "if", "int", "(", "chartGrouping", ")", ">=", "dbtypes", ".", "NumIntervals", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "chartGrouping", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "var", "cd", "*", "dbtypes", ".", "ChartsData", "\n", "switch", "addrChart", "{", "case", "dbtypes", ".", "TxsType", ":", "cd", "=", "d", ".", "history", ".", "TypeByInterval", "[", "chartGrouping", "]", "\n", "case", "dbtypes", ".", "AmountFlow", ":", "cd", "=", "d", ".", "history", ".", "AmtFlowByInterval", "[", "chartGrouping", "]", "\n", "}", "\n\n", "if", "cd", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "cd", ",", "d", ".", "blockID", "(", ")", "\n", "}" ]
// HistoryChart is a thread-safe accessor for the TxHistory.
[ "HistoryChart", "is", "a", "thread", "-", "safe", "accessor", "for", "the", "TxHistory", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L445-L466
train
decred/dcrdata
db/cache/addresscache.go
setBlock
func (d *AddressCacheItem) setBlock(block BlockID) { if block.Hash == d.hash { return } d.hash = block.Hash d.height = block.Height d.utxos = nil d.history.Clear() d.balance = nil d.rows = nil }
go
func (d *AddressCacheItem) setBlock(block BlockID) { if block.Hash == d.hash { return } d.hash = block.Hash d.height = block.Height d.utxos = nil d.history.Clear() d.balance = nil d.rows = nil }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "setBlock", "(", "block", "BlockID", ")", "{", "if", "block", ".", "Hash", "==", "d", ".", "hash", "{", "return", "\n", "}", "\n", "d", ".", "hash", "=", "block", ".", "Hash", "\n", "d", ".", "height", "=", "block", ".", "Height", "\n", "d", ".", "utxos", "=", "nil", "\n", "d", ".", "history", ".", "Clear", "(", ")", "\n", "d", ".", "balance", "=", "nil", "\n", "d", ".", "rows", "=", "nil", "\n", "}" ]
// setBlock ensures that the AddressCacheItem pertains to the given BlockID, // clearing any cached data if the previously set block is not equal to the // given block.
[ "setBlock", "ensures", "that", "the", "AddressCacheItem", "pertains", "to", "the", "given", "BlockID", "clearing", "any", "cached", "data", "if", "the", "previously", "set", "block", "is", "not", "equal", "to", "the", "given", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L551-L561
train
decred/dcrdata
db/cache/addresscache.go
SetRows
func (d *AddressCacheItem) SetRows(block BlockID, rows []dbtypes.AddressRowCompact) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.rows = rows }
go
func (d *AddressCacheItem) SetRows(block BlockID, rows []dbtypes.AddressRowCompact) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.rows = rows }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "SetRows", "(", "block", "BlockID", ",", "rows", "[", "]", "dbtypes", ".", "AddressRowCompact", ")", "{", "d", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "Unlock", "(", ")", "\n", "d", ".", "setBlock", "(", "block", ")", "\n", "d", ".", "rows", "=", "rows", "\n", "}" ]
// SetRows updates the cache item for the given non-merged AddressRow slice // valid at the given BlockID.
[ "SetRows", "updates", "the", "cache", "item", "for", "the", "given", "non", "-", "merged", "AddressRow", "slice", "valid", "at", "the", "given", "BlockID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L565-L570
train
decred/dcrdata
db/cache/addresscache.go
SetUTXOs
func (d *AddressCacheItem) SetUTXOs(block BlockID, utxos []apitypes.AddressTxnOutput) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.utxos = utxos }
go
func (d *AddressCacheItem) SetUTXOs(block BlockID, utxos []apitypes.AddressTxnOutput) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.utxos = utxos }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "SetUTXOs", "(", "block", "BlockID", ",", "utxos", "[", "]", "apitypes", ".", "AddressTxnOutput", ")", "{", "d", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "Unlock", "(", ")", "\n", "d", ".", "setBlock", "(", "block", ")", "\n", "d", ".", "utxos", "=", "utxos", "\n", "}" ]
// SetUTXOs updates the cache item for the given AddressTxnOutput slice valid at // the given BlockID.
[ "SetUTXOs", "updates", "the", "cache", "item", "for", "the", "given", "AddressTxnOutput", "slice", "valid", "at", "the", "given", "BlockID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L574-L579
train
decred/dcrdata
db/cache/addresscache.go
SetBalance
func (d *AddressCacheItem) SetBalance(block BlockID, balance *dbtypes.AddressBalance) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.balance = balance }
go
func (d *AddressCacheItem) SetBalance(block BlockID, balance *dbtypes.AddressBalance) { d.mtx.Lock() defer d.mtx.Unlock() d.setBlock(block) d.balance = balance }
[ "func", "(", "d", "*", "AddressCacheItem", ")", "SetBalance", "(", "block", "BlockID", ",", "balance", "*", "dbtypes", ".", "AddressBalance", ")", "{", "d", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mtx", ".", "Unlock", "(", ")", "\n", "d", ".", "setBlock", "(", "block", ")", "\n", "d", ".", "balance", "=", "balance", "\n", "}" ]
// SetBalance updates the cache item for the given AddressBalance valid at the // given BlockID.
[ "SetBalance", "updates", "the", "cache", "item", "for", "the", "given", "AddressBalance", "valid", "at", "the", "given", "BlockID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L583-L588
train
decred/dcrdata
db/cache/addresscache.go
NewAddressCache
func NewAddressCache(rowCapacity int) *AddressCache { if rowCapacity < 0 { rowCapacity = 0 } ac := &AddressCache{ a: make(map[string]*AddressCacheItem), cap: rowCapacity, capAddr: addressCapacity, } defer func() { go ac.Reporter() }() return ac }
go
func NewAddressCache(rowCapacity int) *AddressCache { if rowCapacity < 0 { rowCapacity = 0 } ac := &AddressCache{ a: make(map[string]*AddressCacheItem), cap: rowCapacity, capAddr: addressCapacity, } defer func() { go ac.Reporter() }() return ac }
[ "func", "NewAddressCache", "(", "rowCapacity", "int", ")", "*", "AddressCache", "{", "if", "rowCapacity", "<", "0", "{", "rowCapacity", "=", "0", "\n", "}", "\n", "ac", ":=", "&", "AddressCache", "{", "a", ":", "make", "(", "map", "[", "string", "]", "*", "AddressCacheItem", ")", ",", "cap", ":", "rowCapacity", ",", "capAddr", ":", "addressCapacity", ",", "}", "\n", "defer", "func", "(", ")", "{", "go", "ac", ".", "Reporter", "(", ")", "}", "(", ")", "\n", "return", "ac", "\n", "}" ]
// NewAddressCache constructs an AddressCache with capacity for the specified // number of address rows.
[ "NewAddressCache", "constructs", "an", "AddressCache", "with", "capacity", "for", "the", "specified", "number", "of", "address", "rows", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L693-L704
train
decred/dcrdata
db/cache/addresscache.go
Reporter
func (ac *AddressCache) Reporter() { var lastBH, lastBM, lastRH, lastRM, lastUH, lastUM, lastHH, lastHM int ticker := time.NewTicker(4 * time.Second) for range ticker.C { balHits, balMisses := ac.BalanceStats() rowHits, rowMisses := ac.RowStats() utxoHits, utxoMisses := ac.UtxoStats() histHits, histMisses := ac.HistoryStats() // Only report if a hit/miss count has changed. if balHits != lastBH || balMisses != lastBM || rowHits != lastRH || rowMisses != lastRM || utxoHits != lastUH || utxoMisses != lastUM || histHits != lastHH || histMisses != lastHM { lastBH, lastBM = balHits, balMisses lastRH, lastRM = rowHits, rowMisses lastUH, lastUM = utxoHits, utxoMisses lastHH, lastHM = histHits, histMisses numAddrs, numRows, numUTXOs := ac.Length() log.Debugf("ADDRESS CACHE: addresses = %d, rows = %d, utxos = %d", numAddrs, numRows, numUTXOs) log.Debugf("ADDRESS CACHE:"+ "\n\t\t\t\t\t HITS | MISSES"+ "\n\t\t\t\t\trows %8d | %6d"+ "\n\t\t\t\t\tbalance %8d | %6d"+ "\n\t\t\t\t\tutxos %8d | %6d"+ "\n\t\t\t\t\thist %8d | %6d", rowHits, rowMisses, balHits, balMisses, utxoHits, utxoMisses, histHits, histMisses) } } }
go
func (ac *AddressCache) Reporter() { var lastBH, lastBM, lastRH, lastRM, lastUH, lastUM, lastHH, lastHM int ticker := time.NewTicker(4 * time.Second) for range ticker.C { balHits, balMisses := ac.BalanceStats() rowHits, rowMisses := ac.RowStats() utxoHits, utxoMisses := ac.UtxoStats() histHits, histMisses := ac.HistoryStats() // Only report if a hit/miss count has changed. if balHits != lastBH || balMisses != lastBM || rowHits != lastRH || rowMisses != lastRM || utxoHits != lastUH || utxoMisses != lastUM || histHits != lastHH || histMisses != lastHM { lastBH, lastBM = balHits, balMisses lastRH, lastRM = rowHits, rowMisses lastUH, lastUM = utxoHits, utxoMisses lastHH, lastHM = histHits, histMisses numAddrs, numRows, numUTXOs := ac.Length() log.Debugf("ADDRESS CACHE: addresses = %d, rows = %d, utxos = %d", numAddrs, numRows, numUTXOs) log.Debugf("ADDRESS CACHE:"+ "\n\t\t\t\t\t HITS | MISSES"+ "\n\t\t\t\t\trows %8d | %6d"+ "\n\t\t\t\t\tbalance %8d | %6d"+ "\n\t\t\t\t\tutxos %8d | %6d"+ "\n\t\t\t\t\thist %8d | %6d", rowHits, rowMisses, balHits, balMisses, utxoHits, utxoMisses, histHits, histMisses) } } }
[ "func", "(", "ac", "*", "AddressCache", ")", "Reporter", "(", ")", "{", "var", "lastBH", ",", "lastBM", ",", "lastRH", ",", "lastRM", ",", "lastUH", ",", "lastUM", ",", "lastHH", ",", "lastHM", "int", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "4", "*", "time", ".", "Second", ")", "\n", "for", "range", "ticker", ".", "C", "{", "balHits", ",", "balMisses", ":=", "ac", ".", "BalanceStats", "(", ")", "\n", "rowHits", ",", "rowMisses", ":=", "ac", ".", "RowStats", "(", ")", "\n", "utxoHits", ",", "utxoMisses", ":=", "ac", ".", "UtxoStats", "(", ")", "\n", "histHits", ",", "histMisses", ":=", "ac", ".", "HistoryStats", "(", ")", "\n", "// Only report if a hit/miss count has changed.", "if", "balHits", "!=", "lastBH", "||", "balMisses", "!=", "lastBM", "||", "rowHits", "!=", "lastRH", "||", "rowMisses", "!=", "lastRM", "||", "utxoHits", "!=", "lastUH", "||", "utxoMisses", "!=", "lastUM", "||", "histHits", "!=", "lastHH", "||", "histMisses", "!=", "lastHM", "{", "lastBH", ",", "lastBM", "=", "balHits", ",", "balMisses", "\n", "lastRH", ",", "lastRM", "=", "rowHits", ",", "rowMisses", "\n", "lastUH", ",", "lastUM", "=", "utxoHits", ",", "utxoMisses", "\n", "lastHH", ",", "lastHM", "=", "histHits", ",", "histMisses", "\n", "numAddrs", ",", "numRows", ",", "numUTXOs", ":=", "ac", ".", "Length", "(", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "numAddrs", ",", "numRows", ",", "numUTXOs", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\\n", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", "+", "\"", "\\n", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", "+", "\"", "\\n", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", "+", "\"", "\\n", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", "+", "\"", "\\n", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", ",", "rowHits", ",", "rowMisses", ",", "balHits", ",", "balMisses", ",", "utxoHits", ",", "utxoMisses", ",", "histHits", ",", "histMisses", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Reporter prints the number of cached addresses, rows, and utxos, as well as a // table of cache hits and misses.
[ "Reporter", "prints", "the", "number", "of", "cached", "addresses", "rows", "and", "utxos", "as", "well", "as", "a", "table", "of", "cache", "hits", "and", "misses", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L728-L758
train
decred/dcrdata
db/cache/addresscache.go
addressCacheItem
func (ac *AddressCache) addressCacheItem(addr string) *AddressCacheItem { ac.mtx.RLock() defer ac.mtx.RUnlock() return ac.a[addr] }
go
func (ac *AddressCache) addressCacheItem(addr string) *AddressCacheItem { ac.mtx.RLock() defer ac.mtx.RUnlock() return ac.a[addr] }
[ "func", "(", "ac", "*", "AddressCache", ")", "addressCacheItem", "(", "addr", "string", ")", "*", "AddressCacheItem", "{", "ac", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "ac", ".", "a", "[", "addr", "]", "\n", "}" ]
// addressCacheItem safely accesses any AddressCacheItem for the given address.
[ "addressCacheItem", "safely", "accesses", "any", "AddressCacheItem", "for", "the", "given", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L761-L765
train
decred/dcrdata
db/cache/addresscache.go
ClearAll
func (ac *AddressCache) ClearAll() (numCleared int) { ac.mtx.Lock() defer ac.mtx.Unlock() numCleared = len(ac.a) ac.a = make(map[string]*AddressCacheItem) return }
go
func (ac *AddressCache) ClearAll() (numCleared int) { ac.mtx.Lock() defer ac.mtx.Unlock() numCleared = len(ac.a) ac.a = make(map[string]*AddressCacheItem) return }
[ "func", "(", "ac", "*", "AddressCache", ")", "ClearAll", "(", ")", "(", "numCleared", "int", ")", "{", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n", "numCleared", "=", "len", "(", "ac", ".", "a", ")", "\n", "ac", ".", "a", "=", "make", "(", "map", "[", "string", "]", "*", "AddressCacheItem", ")", "\n", "return", "\n", "}" ]
// ClearAll resets AddressCache, purging all cached data.
[ "ClearAll", "resets", "AddressCache", "purging", "all", "cached", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L768-L774
train
decred/dcrdata
db/cache/addresscache.go
Clear
func (ac *AddressCache) Clear(addrs []string) (numCleared int) { if addrs == nil { return ac.ClearAll() } if len(addrs) == 0 { return } ac.mtx.Lock() defer ac.mtx.Unlock() for i := range addrs { delete(ac.a, addrs[i]) numCleared++ } return }
go
func (ac *AddressCache) Clear(addrs []string) (numCleared int) { if addrs == nil { return ac.ClearAll() } if len(addrs) == 0 { return } ac.mtx.Lock() defer ac.mtx.Unlock() for i := range addrs { delete(ac.a, addrs[i]) numCleared++ } return }
[ "func", "(", "ac", "*", "AddressCache", ")", "Clear", "(", "addrs", "[", "]", "string", ")", "(", "numCleared", "int", ")", "{", "if", "addrs", "==", "nil", "{", "return", "ac", ".", "ClearAll", "(", ")", "\n", "}", "\n", "if", "len", "(", "addrs", ")", "==", "0", "{", "return", "\n", "}", "\n", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n", "for", "i", ":=", "range", "addrs", "{", "delete", "(", "ac", ".", "a", ",", "addrs", "[", "i", "]", ")", "\n", "numCleared", "++", "\n", "}", "\n", "return", "\n", "}" ]
// Clear purging cached data for the given addresses. If addrs is nil, all data // are cleared. If addresses is non-nil empty slice, no data are cleard.
[ "Clear", "purging", "cached", "data", "for", "the", "given", "addresses", ".", "If", "addrs", "is", "nil", "all", "data", "are", "cleared", ".", "If", "addresses", "is", "non", "-", "nil", "empty", "slice", "no", "data", "are", "cleard", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L778-L792
train
decred/dcrdata
db/cache/addresscache.go
Balance
func (ac *AddressCache) Balance(addr string) (*dbtypes.AddressBalance, *BlockID) { aci := ac.addressCacheItem(addr) if aci == nil { ac.cacheMetrics.BalanceMiss() return nil, nil } ac.cacheMetrics.BalanceHit() return aci.Balance() }
go
func (ac *AddressCache) Balance(addr string) (*dbtypes.AddressBalance, *BlockID) { aci := ac.addressCacheItem(addr) if aci == nil { ac.cacheMetrics.BalanceMiss() return nil, nil } ac.cacheMetrics.BalanceHit() return aci.Balance() }
[ "func", "(", "ac", "*", "AddressCache", ")", "Balance", "(", "addr", "string", ")", "(", "*", "dbtypes", ".", "AddressBalance", ",", "*", "BlockID", ")", "{", "aci", ":=", "ac", ".", "addressCacheItem", "(", "addr", ")", "\n", "if", "aci", "==", "nil", "{", "ac", ".", "cacheMetrics", ".", "BalanceMiss", "(", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n", "ac", ".", "cacheMetrics", ".", "BalanceHit", "(", ")", "\n", "return", "aci", ".", "Balance", "(", ")", "\n", "}" ]
// Balance attempts to retrieve an AddressBalance for the given address. The // BlockID for the block at which the cached data is valid is also returned. In // the event of a cache miss, both returned pointers will be nil.
[ "Balance", "attempts", "to", "retrieve", "an", "AddressBalance", "for", "the", "given", "address", ".", "The", "BlockID", "for", "the", "block", "at", "which", "the", "cached", "data", "is", "valid", "is", "also", "returned", ".", "In", "the", "event", "of", "a", "cache", "miss", "both", "returned", "pointers", "will", "be", "nil", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L797-L805
train
decred/dcrdata
db/cache/addresscache.go
HistoryChart
func (ac *AddressCache) HistoryChart(addr string, addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping) (*dbtypes.ChartsData, *BlockID) { aci := ac.addressCacheItem(addr) if aci == nil { ac.cacheMetrics.HistoryMiss() return nil, nil } cd, blockID := aci.HistoryChart(addrChart, chartGrouping) if cd == nil || blockID == nil { ac.cacheMetrics.HistoryMiss() return nil, nil } ac.cacheMetrics.HistoryHit() return cd, blockID }
go
func (ac *AddressCache) HistoryChart(addr string, addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping) (*dbtypes.ChartsData, *BlockID) { aci := ac.addressCacheItem(addr) if aci == nil { ac.cacheMetrics.HistoryMiss() return nil, nil } cd, blockID := aci.HistoryChart(addrChart, chartGrouping) if cd == nil || blockID == nil { ac.cacheMetrics.HistoryMiss() return nil, nil } ac.cacheMetrics.HistoryHit() return cd, blockID }
[ "func", "(", "ac", "*", "AddressCache", ")", "HistoryChart", "(", "addr", "string", ",", "addrChart", "dbtypes", ".", "HistoryChart", ",", "chartGrouping", "dbtypes", ".", "TimeBasedGrouping", ")", "(", "*", "dbtypes", ".", "ChartsData", ",", "*", "BlockID", ")", "{", "aci", ":=", "ac", ".", "addressCacheItem", "(", "addr", ")", "\n", "if", "aci", "==", "nil", "{", "ac", ".", "cacheMetrics", ".", "HistoryMiss", "(", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "cd", ",", "blockID", ":=", "aci", ".", "HistoryChart", "(", "addrChart", ",", "chartGrouping", ")", "\n", "if", "cd", "==", "nil", "||", "blockID", "==", "nil", "{", "ac", ".", "cacheMetrics", ".", "HistoryMiss", "(", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "ac", ".", "cacheMetrics", ".", "HistoryHit", "(", ")", "\n", "return", "cd", ",", "blockID", "\n", "}" ]
// HistoryChart attempts to retrieve ChartsData for the given address, chart // type, and grouping inverval. The BlockID for the block at which the cached // data is valid is also returned. In the event of a cache miss, both returned // pointers will be nil.
[ "HistoryChart", "attempts", "to", "retrieve", "ChartsData", "for", "the", "given", "address", "chart", "type", "and", "grouping", "inverval", ".", "The", "BlockID", "for", "the", "block", "at", "which", "the", "cached", "data", "is", "valid", "is", "also", "returned", ".", "In", "the", "event", "of", "a", "cache", "miss", "both", "returned", "pointers", "will", "be", "nil", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L824-L840
train
decred/dcrdata
db/cache/addresscache.go
Length
func (ac *AddressCache) Length() (numAddrs, numTxns, numUTXOs int) { ac.mtx.RLock() defer ac.mtx.RUnlock() return ac.length() }
go
func (ac *AddressCache) Length() (numAddrs, numTxns, numUTXOs int) { ac.mtx.RLock() defer ac.mtx.RUnlock() return ac.length() }
[ "func", "(", "ac", "*", "AddressCache", ")", "Length", "(", ")", "(", "numAddrs", ",", "numTxns", ",", "numUTXOs", "int", ")", "{", "ac", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "ac", ".", "length", "(", ")", "\n", "}" ]
// Length returns the total number of address rows and UTXOs stored in cache.
[ "Length", "returns", "the", "total", "number", "of", "address", "rows", "and", "UTXOs", "stored", "in", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L948-L952
train
decred/dcrdata
db/cache/addresscache.go
NumAddresses
func (ac *AddressCache) NumAddresses() int { ac.mtx.RLock() defer ac.mtx.RUnlock() return len(ac.a) }
go
func (ac *AddressCache) NumAddresses() int { ac.mtx.RLock() defer ac.mtx.RUnlock() return len(ac.a) }
[ "func", "(", "ac", "*", "AddressCache", ")", "NumAddresses", "(", ")", "int", "{", "ac", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "ac", ".", "a", ")", "\n", "}" ]
// NumAddresses returns the total number of addresses in the cache.
[ "NumAddresses", "returns", "the", "total", "number", "of", "addresses", "in", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L955-L959
train
decred/dcrdata
db/cache/addresscache.go
StoreRows
func (ac *AddressCache) StoreRows(addr string, rows []*dbtypes.AddressRow, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } rowsCompact := []dbtypes.AddressRowCompact{} if rows != nil { rowsCompact = dbtypes.CompactRows(rows) } // respect cache capacity return ac.StoreRowsCompact(addr, rowsCompact, block) }
go
func (ac *AddressCache) StoreRows(addr string, rows []*dbtypes.AddressRow, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } rowsCompact := []dbtypes.AddressRowCompact{} if rows != nil { rowsCompact = dbtypes.CompactRows(rows) } // respect cache capacity return ac.StoreRowsCompact(addr, rowsCompact, block) }
[ "func", "(", "ac", "*", "AddressCache", ")", "StoreRows", "(", "addr", "string", ",", "rows", "[", "]", "*", "dbtypes", ".", "AddressRow", ",", "block", "*", "BlockID", ")", "bool", "{", "if", "block", "==", "nil", "||", "ac", ".", "cap", "<", "1", "||", "ac", ".", "capAddr", "<", "1", "{", "return", "false", "\n", "}", "\n\n", "rowsCompact", ":=", "[", "]", "dbtypes", ".", "AddressRowCompact", "{", "}", "\n", "if", "rows", "!=", "nil", "{", "rowsCompact", "=", "dbtypes", ".", "CompactRows", "(", "rows", ")", "\n", "}", "\n\n", "// respect cache capacity", "return", "ac", ".", "StoreRowsCompact", "(", "addr", ",", "rowsCompact", ",", "block", ")", "\n", "}" ]
// StoreRows stores the non-merged AddressRow slice for the given address in // cache. The current best block data is required to determine cache freshness.
[ "StoreRows", "stores", "the", "non", "-", "merged", "AddressRow", "slice", "for", "the", "given", "address", "in", "cache", ".", "The", "current", "best", "block", "data", "is", "required", "to", "determine", "cache", "freshness", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L1071-L1083
train
decred/dcrdata
db/cache/addresscache.go
StoreHistoryChart
func (ac *AddressCache) StoreHistoryChart(addr string, addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping, cd *dbtypes.ChartsData, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } if int(chartGrouping) >= dbtypes.NumIntervals { log.Errorf("Invalid chart grouping: %v", chartGrouping) return false } if cd == nil { cd = &dbtypes.ChartsData{} } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if aci == nil || aci.BlockHash() != block.Hash { aci = &AddressCacheItem{ height: block.Height, hash: block.Hash, } if !ac.addCacheItem(addr, aci) { return false } } // Set the history data in the cache item. aci.mtx.Lock() defer aci.mtx.Unlock() switch addrChart { case dbtypes.TxsType: aci.history.TypeByInterval[chartGrouping] = cd case dbtypes.AmountFlow: aci.history.AmtFlowByInterval[chartGrouping] = cd default: return false } return true }
go
func (ac *AddressCache) StoreHistoryChart(addr string, addrChart dbtypes.HistoryChart, chartGrouping dbtypes.TimeBasedGrouping, cd *dbtypes.ChartsData, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } if int(chartGrouping) >= dbtypes.NumIntervals { log.Errorf("Invalid chart grouping: %v", chartGrouping) return false } if cd == nil { cd = &dbtypes.ChartsData{} } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if aci == nil || aci.BlockHash() != block.Hash { aci = &AddressCacheItem{ height: block.Height, hash: block.Hash, } if !ac.addCacheItem(addr, aci) { return false } } // Set the history data in the cache item. aci.mtx.Lock() defer aci.mtx.Unlock() switch addrChart { case dbtypes.TxsType: aci.history.TypeByInterval[chartGrouping] = cd case dbtypes.AmountFlow: aci.history.AmtFlowByInterval[chartGrouping] = cd default: return false } return true }
[ "func", "(", "ac", "*", "AddressCache", ")", "StoreHistoryChart", "(", "addr", "string", ",", "addrChart", "dbtypes", ".", "HistoryChart", ",", "chartGrouping", "dbtypes", ".", "TimeBasedGrouping", ",", "cd", "*", "dbtypes", ".", "ChartsData", ",", "block", "*", "BlockID", ")", "bool", "{", "if", "block", "==", "nil", "||", "ac", ".", "cap", "<", "1", "||", "ac", ".", "capAddr", "<", "1", "{", "return", "false", "\n", "}", "\n\n", "if", "int", "(", "chartGrouping", ")", ">=", "dbtypes", ".", "NumIntervals", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "chartGrouping", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "cd", "==", "nil", "{", "cd", "=", "&", "dbtypes", ".", "ChartsData", "{", "}", "\n", "}", "\n\n", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n", "aci", ":=", "ac", ".", "a", "[", "addr", "]", "\n\n", "if", "aci", "==", "nil", "||", "aci", ".", "BlockHash", "(", ")", "!=", "block", ".", "Hash", "{", "aci", "=", "&", "AddressCacheItem", "{", "height", ":", "block", ".", "Height", ",", "hash", ":", "block", ".", "Hash", ",", "}", "\n", "if", "!", "ac", ".", "addCacheItem", "(", "addr", ",", "aci", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// Set the history data in the cache item.", "aci", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "aci", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "switch", "addrChart", "{", "case", "dbtypes", ".", "TxsType", ":", "aci", ".", "history", ".", "TypeByInterval", "[", "chartGrouping", "]", "=", "cd", "\n", "case", "dbtypes", ".", "AmountFlow", ":", "aci", ".", "history", ".", "AmtFlowByInterval", "[", "chartGrouping", "]", "=", "cd", "\n", "default", ":", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// StoreHistoryChart stores the charts data for the given address in cache. The // current best block data is required to determine cache freshness.
[ "StoreHistoryChart", "stores", "the", "charts", "data", "for", "the", "given", "address", "in", "cache", ".", "The", "current", "best", "block", "data", "is", "required", "to", "determine", "cache", "freshness", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L1087-L1130
train
decred/dcrdata
db/cache/addresscache.go
StoreRowsCompact
func (ac *AddressCache) StoreRowsCompact(addr string, rows []dbtypes.AddressRowCompact, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } ac.mtx.Lock() defer ac.mtx.Unlock() if rows == nil { rows = []dbtypes.AddressRowCompact{} } // respect cache capacity return ac.setCacheItemRows(addr, rows, block) }
go
func (ac *AddressCache) StoreRowsCompact(addr string, rows []dbtypes.AddressRowCompact, block *BlockID) bool { if block == nil || ac.cap < 1 || ac.capAddr < 1 { return false } ac.mtx.Lock() defer ac.mtx.Unlock() if rows == nil { rows = []dbtypes.AddressRowCompact{} } // respect cache capacity return ac.setCacheItemRows(addr, rows, block) }
[ "func", "(", "ac", "*", "AddressCache", ")", "StoreRowsCompact", "(", "addr", "string", ",", "rows", "[", "]", "dbtypes", ".", "AddressRowCompact", ",", "block", "*", "BlockID", ")", "bool", "{", "if", "block", "==", "nil", "||", "ac", ".", "cap", "<", "1", "||", "ac", ".", "capAddr", "<", "1", "{", "return", "false", "\n", "}", "\n\n", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "if", "rows", "==", "nil", "{", "rows", "=", "[", "]", "dbtypes", ".", "AddressRowCompact", "{", "}", "\n", "}", "\n\n", "// respect cache capacity", "return", "ac", ".", "setCacheItemRows", "(", "addr", ",", "rows", ",", "block", ")", "\n", "}" ]
// StoreRowsCompact stores the non-merged AddressRow slice for the given address // in cache. The current best block data is required to determine cache // freshness.
[ "StoreRowsCompact", "stores", "the", "non", "-", "merged", "AddressRow", "slice", "for", "the", "given", "address", "in", "cache", ".", "The", "current", "best", "block", "data", "is", "required", "to", "determine", "cache", "freshness", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L1135-L1149
train
decred/dcrdata
db/cache/addresscache.go
StoreBalance
func (ac *AddressCache) StoreBalance(addr string, balance *dbtypes.AddressBalance, block *BlockID) bool { if ac.cap < 1 || ac.capAddr < 1 { return false } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if block != nil && balance == nil { balance = &dbtypes.AddressBalance{ Address: addr, } } if aci == nil || aci.BlockHash() != block.Hash { return ac.addCacheItem(addr, &AddressCacheItem{ balance: balance, height: block.Height, hash: block.Hash, }) } // cache is current, so just set the balance. aci.mtx.Lock() aci.balance = balance aci.mtx.Unlock() return true }
go
func (ac *AddressCache) StoreBalance(addr string, balance *dbtypes.AddressBalance, block *BlockID) bool { if ac.cap < 1 || ac.capAddr < 1 { return false } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if block != nil && balance == nil { balance = &dbtypes.AddressBalance{ Address: addr, } } if aci == nil || aci.BlockHash() != block.Hash { return ac.addCacheItem(addr, &AddressCacheItem{ balance: balance, height: block.Height, hash: block.Hash, }) } // cache is current, so just set the balance. aci.mtx.Lock() aci.balance = balance aci.mtx.Unlock() return true }
[ "func", "(", "ac", "*", "AddressCache", ")", "StoreBalance", "(", "addr", "string", ",", "balance", "*", "dbtypes", ".", "AddressBalance", ",", "block", "*", "BlockID", ")", "bool", "{", "if", "ac", ".", "cap", "<", "1", "||", "ac", ".", "capAddr", "<", "1", "{", "return", "false", "\n", "}", "\n\n", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n", "aci", ":=", "ac", ".", "a", "[", "addr", "]", "\n\n", "if", "block", "!=", "nil", "&&", "balance", "==", "nil", "{", "balance", "=", "&", "dbtypes", ".", "AddressBalance", "{", "Address", ":", "addr", ",", "}", "\n", "}", "\n\n", "if", "aci", "==", "nil", "||", "aci", ".", "BlockHash", "(", ")", "!=", "block", ".", "Hash", "{", "return", "ac", ".", "addCacheItem", "(", "addr", ",", "&", "AddressCacheItem", "{", "balance", ":", "balance", ",", "height", ":", "block", ".", "Height", ",", "hash", ":", "block", ".", "Hash", ",", "}", ")", "\n", "}", "\n\n", "// cache is current, so just set the balance.", "aci", ".", "mtx", ".", "Lock", "(", ")", "\n", "aci", ".", "balance", "=", "balance", "\n", "aci", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}" ]
// StoreBalance stores the AddressBalance for the given address in cache. The // current best block data is required to determine cache freshness.
[ "StoreBalance", "stores", "the", "AddressBalance", "for", "the", "given", "address", "in", "cache", ".", "The", "current", "best", "block", "data", "is", "required", "to", "determine", "cache", "freshness", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L1153-L1181
train
decred/dcrdata
db/cache/addresscache.go
StoreUTXOs
func (ac *AddressCache) StoreUTXOs(addr string, utxos []apitypes.AddressTxnOutput, block *BlockID) bool { if ac.cap < 1 || ac.capAddr < 1 { return false } // Only allow storing maxUTXOsPerAddr. if len(utxos) > maxUTXOsPerAddr && addr != ac.ProjectAddress { return false } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if block != nil && utxos == nil { utxos = []apitypes.AddressTxnOutput{} } if aci == nil || aci.BlockHash() != block.Hash { return ac.addCacheItem(addr, &AddressCacheItem{ utxos: utxos, height: block.Height, hash: block.Hash, }) } // cache is current, so just set the utxos. aci.mtx.Lock() aci.utxos = utxos aci.mtx.Unlock() return true }
go
func (ac *AddressCache) StoreUTXOs(addr string, utxos []apitypes.AddressTxnOutput, block *BlockID) bool { if ac.cap < 1 || ac.capAddr < 1 { return false } // Only allow storing maxUTXOsPerAddr. if len(utxos) > maxUTXOsPerAddr && addr != ac.ProjectAddress { return false } ac.mtx.Lock() defer ac.mtx.Unlock() aci := ac.a[addr] if block != nil && utxos == nil { utxos = []apitypes.AddressTxnOutput{} } if aci == nil || aci.BlockHash() != block.Hash { return ac.addCacheItem(addr, &AddressCacheItem{ utxos: utxos, height: block.Height, hash: block.Hash, }) } // cache is current, so just set the utxos. aci.mtx.Lock() aci.utxos = utxos aci.mtx.Unlock() return true }
[ "func", "(", "ac", "*", "AddressCache", ")", "StoreUTXOs", "(", "addr", "string", ",", "utxos", "[", "]", "apitypes", ".", "AddressTxnOutput", ",", "block", "*", "BlockID", ")", "bool", "{", "if", "ac", ".", "cap", "<", "1", "||", "ac", ".", "capAddr", "<", "1", "{", "return", "false", "\n", "}", "\n\n", "// Only allow storing maxUTXOsPerAddr.", "if", "len", "(", "utxos", ")", ">", "maxUTXOsPerAddr", "&&", "addr", "!=", "ac", ".", "ProjectAddress", "{", "return", "false", "\n", "}", "\n\n", "ac", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ac", ".", "mtx", ".", "Unlock", "(", ")", "\n", "aci", ":=", "ac", ".", "a", "[", "addr", "]", "\n\n", "if", "block", "!=", "nil", "&&", "utxos", "==", "nil", "{", "utxos", "=", "[", "]", "apitypes", ".", "AddressTxnOutput", "{", "}", "\n", "}", "\n\n", "if", "aci", "==", "nil", "||", "aci", ".", "BlockHash", "(", ")", "!=", "block", ".", "Hash", "{", "return", "ac", ".", "addCacheItem", "(", "addr", ",", "&", "AddressCacheItem", "{", "utxos", ":", "utxos", ",", "height", ":", "block", ".", "Height", ",", "hash", ":", "block", ".", "Hash", ",", "}", ")", "\n", "}", "\n\n", "// cache is current, so just set the utxos.", "aci", ".", "mtx", ".", "Lock", "(", ")", "\n", "aci", ".", "utxos", "=", "utxos", "\n", "aci", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}" ]
// StoreUTXOs stores the AddressTxnOutput slice for the given address in cache. // The current best block data is required to determine cache freshness.
[ "StoreUTXOs", "stores", "the", "AddressTxnOutput", "slice", "for", "the", "given", "address", "in", "cache", ".", "The", "current", "best", "block", "data", "is", "required", "to", "determine", "cache", "freshness", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/cache/addresscache.go#L1185-L1216
train
decred/dcrdata
api/insight/converter.go
TxConverter
func (iapi *InsightApi) TxConverter(txs []*dcrjson.TxRawResult) ([]apitypes.InsightTx, error) { return iapi.DcrToInsightTxns(txs, false, false, false) }
go
func (iapi *InsightApi) TxConverter(txs []*dcrjson.TxRawResult) ([]apitypes.InsightTx, error) { return iapi.DcrToInsightTxns(txs, false, false, false) }
[ "func", "(", "iapi", "*", "InsightApi", ")", "TxConverter", "(", "txs", "[", "]", "*", "dcrjson", ".", "TxRawResult", ")", "(", "[", "]", "apitypes", ".", "InsightTx", ",", "error", ")", "{", "return", "iapi", ".", "DcrToInsightTxns", "(", "txs", ",", "false", ",", "false", ",", "false", ")", "\n", "}" ]
// TxConverter converts dcrd-tx to insight tx
[ "TxConverter", "converts", "dcrd", "-", "tx", "to", "insight", "tx" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/converter.go#L15-L17
train