tlab-trading-toolkit
Version:
A trading toolkit for building advanced trading bots on the GDAX platform
876 lines (853 loc) • 157 kB
TypeScript
// Generated by dts-bundle v0.7.3
// Dependencies for this module:
// ../pushbullet
// ../stream
// ../ws
// ../events
// ../bignumber.js
// ../bintrees
// ../superagent
import * as PushBullet from 'pushbullet';
import { Duplex } from 'stream';
import { Writable } from 'stream';
import { Transform } from 'stream';
import { Readable } from 'stream';
import WebSocket = require('ws');
import { EventEmitter } from 'events';
import { BigNumber as BigJS } from 'bignumber.js';
import stream = require('stream');
import { RBTree } from 'bintrees';
import * as BigNumber from 'bignumber.js';
import { NumberLike } from 'bignumber.js';
import { Readable, Writable } from 'stream';
import request = require('superagent');
import superAgent = require('superagent');
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export { Core, Exchanges, Factories, FXService, utils, lib };
/**
* Loggers
*/
/**
* FXService
*/
/**
* GDAX factories
*/
export { GDAX };
/**
* Bitfinex factories
*/
export { Bitfinex };
/**
* Poloniex factories
*/
export { Poloniex };
/**
* Bittrex factories
*/
export { Bittrex };
export { Binance };
export { Gemini };
export const Providers: {
CoinMarketCapProvider: typeof CoinMarketCapProvider;
OpenExchangeProvider: typeof OpenExchangeProvider;
YahooFXProvider: typeof YahooFXProvider;
};
export const Calculators: {
SimpleRateCalculator: typeof SimpleRateCalculator;
};
export { PushBullet };
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export interface ExchangeRateFilterConfig extends MessageTransformConfig {
pair: CurrencyPair;
fxService: FXService;
precision: number;
}
/**
* Implements a stream filter that applies an exchange rate to a stream of GDAX messages.
*
*
* If the FXService has any problems and enters an ErrorState, the filter will continue to convert prices, but you
* can watch for FXRateMayBeInvalid events and respond accordingly
*/
export class ExchangeRateFilter extends AbstractMessageTransform {
constructor(config: ExchangeRateFilterConfig);
readonly rate: FXObject;
transformMessage(msg: StreamMessage): StreamMessage;
}
export interface HFTFilterConfig extends MessageTransformConfig {
targetQueueLength: number;
}
export interface HFTFilterStats {
backlog: number;
skippedMessages: number;
tradesSkipped: number;
}
/**
* Filters the raw WS message stream by batching messages and auto-cancelling zero-effect trades.
*
* If you read from this stream in 'push' mode, i.e. by attaching a `data` listener to it, then each message will
* be emitted more/less instantaneously, and so the filtering mechanism won't have time to catch HFTs. The
* way you probably want to use this stream is to always have it paused and call `read` when you want the
* next message (perhaps every n ms). This way, there's maximum opportunity to pre-filter zero-effect trades; and
* re-order any messages that may have arrived out of order
*/
export class HFTFilter extends Duplex {
constructor(config: HFTFilterConfig);
getStats(): HFTFilterStats;
readonly queueLength: number;
readonly numSkippedMessages: number;
read(size?: number): StreamMessage;
/**
* Add the message to the queue
*/
addMessage(message: StreamMessage): boolean;
processDoneMessage(done: BaseOrderMessage): boolean;
processChangeMessage(change: ChangedOrderMessage): boolean;
pop(): StreamMessage;
clearQueue(): void;
protected _read(): void;
/**
* If this stream has another stream piped into it, we just pass the data into the READABLE stream's filter
*/
protected _write(chunk: any, encoding: string, callback: (err: Error) => void): void;
/**
* Returns true if the message Queue has lengthened
*/
protected filterMessage(message: StreamMessage): boolean;
/**
* Simply passes the message onto the output stream
*/
protected passThrough(message: StreamMessage): boolean;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export class LiveBookConfig {
product: string;
strictMode?: boolean;
logger?: Logger;
}
export enum SequenceStatus {
OK = 0,
ALREADY_PROCESSED = 1,
SKIP_DETECTED = 2,
}
export interface SkippedMessageEvent {
sequence: number;
expected_sequence: number;
}
/**
* A live orderbook. This class maintains the state of an orderbook (using BookBuilder) in realtime by responding to
* messages from attached feeds.
*/
export class LiveOrderbook extends Writable implements Orderbook {
readonly product: string;
readonly baseCurrency: string;
readonly quoteCurrency: string;
protected snapshotReceived: boolean;
protected strictMode: boolean;
protected lastBookUpdate: Date;
protected _book: BookBuilder;
protected liveTicker: Ticker;
protected _sourceSequence: number;
constructor(config: LiveBookConfig);
log(level: string, message: string, meta?: any): void;
readonly sourceSequence: number;
readonly numAsks: number;
readonly numBids: number;
readonly bidsTotal: BigJS;
readonly asksTotal: BigJS;
state(): OrderbookState;
readonly book: BookBuilder;
readonly ticker: Ticker;
readonly sequence: number;
/**
*/
readonly timeSinceTickerUpdate: number;
/**
* The time (in seconds) since the last orderbook update
*/
readonly timeSinceOrderbookUpdate: number;
/**
* Return an array of (aggregated) orders whose sum is equal to or greater than `value`. The side parameter is from
* the perspective of the purchaser, so 'buy' returns asks and 'sell' bids.
*/
ordersForValue(side: string, value: Biglike, useQuote: boolean, startPrice?: StartPoint): CumulativePriceLevel[];
protected _read(): void;
_write(msg: any, encoding: string, callback: () => void): void;
protected processTradeMessage(msg: TradeMessage): void;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
/**
* Configuration interface for A MessageQueue
*
* @param logger {Logger} An optional logging interface
*
* @param product {string} A product to filter for. A single feed might be producing messages form multiple products (each with their own
* sequence numbers). This selects for the product so that all messages can be emitted in strictly increasing sequence number.
*
* @param targetQueueLength {number} Tries to maintain the queue length at this value. Default is zero, but you can increase to
* small number like 2 or 3 if messages frequently arrive out of order. This will impose small lag on your feed, but will
* reduce the risk of messages arriving out of order
*
* @param waitForSnapshot If true, messages are queued up until a snapshot message is received. If false, messages are
* emitted in the order they are received without waiting for a snapshot.
*/
export interface MessageQueueConfig {
product: string;
logger?: Logger;
targetQueueLength?: number;
waitForSnapshot: boolean;
}
/**
* The MessageQueue does two things:
* i) Filters input messages for a specific product
* ii) Queues messages, sorts them and emits them in a strictly increasing order.
*
* The source feed can contain multiple product streams. This class will filter out any products that don't match the configured
* product feed. This means you can create a single websocket feed that subscribes to all of, say GDAX's products and then
* create multiple `MessageStreams` without much overhead.
*
* There are three different ways of using the stream:
*
* 1. Push mode: You attach a `data` listener to this stream and each each message will be emitted more/less instantaneously,
* as it is received from the feed. In this case one might still get messages arriving out of order, since the queue is usually
* going to be empty.
* 2. Create the stream in 'paused' mode (the default when you create it) and call `read` when you want the
* next message (perhaps every n ms).
* 3. Pipe the stream to another stream that performs some other function (like filter out HFT trades, or apply an exchange rate)
*
* You can always track out-of-order messages by subscribing to the `messageOutOfSequence` event.
*
* ## Events
*
* ### data(msg)
* Emitted for each message that gets sent out
*
* ### messageOutOfSequence (msg, expectedSequence)
* Emitted if a message is about to be sent out, out of sequence and waiting would violate the `targetQueueLength` constraint
*/
export class MessageQueue extends Duplex {
constructor(options: MessageQueueConfig);
readonly product: string;
readonly queueLength: number;
readonly sequence: number;
read(size?: number): OrderbookMessage;
/**
* Close the stream. No more reads will be possible after calling this method
*/
end(): void;
/**
* Add the message to the queue
* @param message
*/
addMessage(message: OrderbookMessage): void;
clearQueue(): void;
/**
* Will provide the next message, in the correct order
* @private
*/
protected _read(): void;
/**
* Returns the next message off the queue, and removes it from the queue. pop() tries to keep the queue at
* `targetQueueLength` if releasing a message would result in messages being out of order, so its possible for
* pop() to return null
* @returns {OrderbookMessage || null}
*/
protected pop(): OrderbookMessage;
protected _write(inputMessage: any, encoding: string, callback: (err: Error) => void): void;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
/**
* Interfaces for the GTT Stream message types. These messages are generated and passed on my the GTT streaming
* infrastructure. The `type` field is conventionally named after the interface, first letter lowercased, with the word Message
* stripped out, so e.g. HeartbeatMessage => heartbeat and NewOrderMessage => newOrder
*/
export interface StreamMessage {
type: string;
time: Date;
}
export function isStreamMessage(msg: any): boolean;
export interface ErrorMessage {
message: string;
}
export interface UnknownMessage extends StreamMessage {
sequence?: number;
productId?: string;
message: any;
}
/**
* Root definition for messages that stem from a websocket feed
*/
export interface OrderbookMessage extends StreamMessage {
sequence: number;
sourceSequence?: number;
productId: string;
side: string;
}
export function isOrderbookMessage(msg: any): boolean;
/**
* Message representing the common state for a resting order (for an order request, see PlaceOrderRequest)
*/
export interface BaseOrderMessage extends OrderbookMessage {
orderId: string;
price: string;
}
export function isOrderMessage(msg: any): boolean;
/**
* In order-level books, represents a new order.
*
* `orderType` is market, limit, stop
*/
export interface NewOrderMessage extends BaseOrderMessage {
size: string;
}
/**
* In order-level books, means an order has been filled, or cancelled. RemainingSize indicated how much of the order
* was left unfilled if it was cancelled
*/
export interface OrderDoneMessage extends BaseOrderMessage {
reason: string;
remainingSize: string;
}
/**
* In order-level books, means the size of an existing order has changed. Either `newSize` (which replaces the old value)
* or changedAmount (which adds to the old value) must be specified.
*/
export interface ChangedOrderMessage extends BaseOrderMessage {
newSize?: string;
changedAmount?: string;
}
/**
* Represents a price-level change in an orderbook. The `size` parameter represents the new size of the level and should
* replace the old one.
*/
export interface LevelMessage extends OrderbookMessage {
price: string;
size: string;
count: number;
}
/**
* Reflects a trade that has taken place. This message does not impact the orderbook, and as such does not carry a
* sequence field. A corresponding `level`, `done`, or 'change` message will also be sent.
*/
export interface TradeMessage extends StreamMessage {
productId: string;
side: string;
tradeId: string;
price: string;
size: string;
}
export interface SnapshotMessage extends StreamMessage, OrderbookState {
productId: string;
}
export interface TickerMessage extends StreamMessage, Ticker {
productId: string;
}
/**
* A new order request message. Only the most common fields are specified here. Additional options can be specified
* in the extra field, which can be handled by the target trade engine.
*/
export interface PlaceOrderMessage extends StreamMessage {
productId: string;
clientId?: string;
side: string;
orderType: string;
price?: string;
postOnly?: boolean;
size?: string;
funds?: string;
extra?: any;
}
export interface CancelOrderRequestMessage extends StreamMessage {
type: string;
orderId: string;
}
/**
* Emitted from a feed when one of my orders has been matched. (An authenticated feed is required)
*/
export interface TradeExecutedMessage extends StreamMessage {
productId: string;
orderId: string;
side: string;
price: string;
orderType: string;
tradeSize: string;
remainingSize: string;
}
export interface TradeFinalizedMessage extends StreamMessage {
productId: string;
orderId: string;
side: string;
remainingSize: string;
reason: string;
}
export interface MyOrderPlacedMessage extends StreamMessage {
productId: string;
orderId: string;
side: string;
price: string;
orderType: string;
size: string;
sequence: number;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export interface ProductFilterConfig extends MessageTransformConfig {
productId: string;
}
/**
* Filters out any messages that don't have the configured product_id
*/
export class ProductFilter extends AbstractMessageTransform {
productId: string;
constructor(config: ProductFilterConfig);
transformMessage(msg: any): any;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
/**
* A simple transform stream that passes messages through at a specified rate. The timestamp is updated to reflect when
* the message was actually sent
*/
export default class RateLimiter extends Transform {
/**
* Limit outgoing message to `limit` per `interval`
* @param limit The number of messages released per interval
* @param interval The length of an interval in ms
*/
constructor(limit: number, interval: number);
protected _transform(msg: StreamMessage, encoding: string, callback: (err?: Error, data?: any) => void): void;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export interface TraderConfig {
logger: Logger;
exchangeAPI: AuthenticatedExchangeAPI;
productId: string;
fitOrders: boolean;
sizePrecision?: number;
pricePrecision?: number;
}
/**
* The Trader class places orders on your behalf. The commands for placing the trades can either come from an attached
* stream, or directly via the API.
*
* One should have an *authenticated* feed piped into Trader so that it can keep track of the state of its own orderbook.
* Failing this, it is trading 'blind' and will have to rely on REST requests to update the state of the book.
*
* Emitted messages:
* Trader.outOfSyncWarning - The internal order pool and what's actually on the exchange may be out of sync
* Trader.trade-finalized - An order is complete (done)
* Trader.my-orders-cancelled - A call to cancel all orders in this orderbook has completed
* Trader.all-orders-cancelled - A call to cancel ALL of the user's orders (including those placed elsewhere) has been completed
* Trader.order-placed - Emitted after an order has been successfully placed
* Trader.order-cancelled - Emitted after an order has been cancelled
* Trader.trade-executed - emitted after a trade has been executed against my limit order
* Trader.place-order-failed - A REST order request returned with an error
* Trader.cancel-order-failed - A Cancel request returned with an error status
*/
export class Trader extends Writable {
constructor(config: TraderConfig);
readonly productId: string;
fitOrders: boolean;
placeOrder(req: PlaceOrderMessage): Promise<LiveOrder>;
cancelOrder(orderId: string): Promise<string>;
cancelMyOrders(): Promise<string[]>;
/**
* Cancel all, and we mean ALL orders (even those not placed by this Trader). To cancel only the messages
* listed in the in-memory orderbook, use `cancelMyOrders`
*/
cancelAllOrders(): Promise<string[]>;
state(): OrderbookState;
/**
* Compare the state of the in-memory orderbook with the one returned from a REST query of all my orders. The
* result is an `OrderbookState` object that represents the diff between the two states. Negative sizes represent
* orders in-memory that don't exist on the book and positive ones are vice versa
*/
checkState(): Promise<OrderbookState>;
executeMessage(msg: StreamMessage): void;
protected _write(msg: any, encoding: string, callback: (err?: Error) => any): void;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export type Action<T extends StreamMessage> = (event: T) => void;
export type TriggerFilter = (message: StreamMessage) => void;
/**
* A trigger is a small utility class that associates an action with an event. You should seldom use this class
* directly, but will rather use a factory function, such as [[createPriceTrigger]] to generate an appropriate trigger
* for you.
*/
export class Trigger<T extends StreamMessage> {
constructor(feed: ExchangeFeed);
setAction(action: Action<T>): Trigger<T>;
setFilter(filter: TriggerFilter): Trigger<T>;
execute(event: T): Trigger<T>;
cancel(): void;
}
/**
* Creates a new price trigger. The feed and product specify which Ticker messages to watch for. priceThreshold is
* the price which triggers the action when it is crossed. The first price tick after this trigger is created determines
* whether it is a low- or high- price trigger.
*/
export function createPriceTrigger(feed: ExchangeFeed, product: string, priceThreshold: Biglike): Trigger<TickerMessage>;
export function createTickerTrigger(feed: ExchangeFeed, product: string, onlyOnce?: boolean): Trigger<TickerMessage>;
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export class ProductSplitter extends StreamCopier {
constructor(feed: ExchangeFeed, productIds: string[]);
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export class RedisBookConfig extends LiveBookConfig {
exchange: string;
}
export class RedisBook extends LiveOrderbook implements Orderbook {
protected _book: RedisBookBuilder;
constructor(config: RedisBookConfig);
processTradeMessage(msg: TradeMessage): void;
}
export function getClient(): any;
export function getRedisct(): any;
export function getPubSubClient(): any;
export function getEmitter(): any;
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export class ExchangeFeedConfig {
wsUrl: string;
logger: Logger;
auth: ExchangeAuthConfig;
}
export const hooks: {
WebSocket: typeof WebSocket;
};
export abstract class ExchangeFeed extends Readable {
protected auth: ExchangeAuthConfig;
protected url: string;
protected isConnecting: boolean;
protected lastHeartBeat: number;
protected multiSocket: boolean;
protected sockets: WebSocket[];
constructor(config: ExchangeFeedConfig);
readonly logger: Logger;
log(level: string, message: string, meta?: any): void;
isConnected(): boolean;
reconnect(delay: number): void;
disconnect(): void;
protected connect(products?: string[]): void;
protected getWebsocketUrlForProduct(product: string): string;
protected killProcess(msg: any): void;
protected readonly abstract owner: string;
protected abstract handleMessage(msg: string, product?: string): void;
protected abstract onOpen(): void;
protected onClose(code: number, reason: string): void;
protected onError(err: Error): void;
/**
* Called by sub-classes to confirm that the connection is still alive
*/
protected confirmAlive(): void;
protected close(): void;
protected onNewConnection(): void;
/**
* Check that we have received a heartbeat message within the last period ms
*/
protected checkConnection(period: number): void;
/**
* Checks that the auth object provided is fully populated and is valid. Subclasses can override this to provide
* additional validation steps.
*
* This function should return the auth object or `undefined` if it isn't valid.
*/
protected validateAuth(auth: ExchangeAuthConfig): ExchangeAuthConfig;
protected send(msg: any, cb?: (err: Error) => void): void;
protected _read(size: number): void;
}
export interface ExchangeFeedConstructor<T extends ExchangeFeed, U extends ExchangeFeedConfig> {
new (config: U): T;
}
/**
* Get or create a Websocket feed to a GDAX product. A single connection is maintained per URL + auth combination.
* Usually you'll connect to the main GDAX feed by passing in `GDAX_WS_FEED` as the first parameter, but you can create
* additional feeds to the public sandbox, for example by providing the relevant URL; or creating an authenticated and
* public feed (although the authenticated feed also carries public messages)
*/
export function getFeed<T extends ExchangeFeed, U extends ExchangeFeedConfig>(type: ExchangeFeedConstructor<T, U>, config: U): T;
/**
* Create a unique key hash based on URL and credentials
*/
export function getKey(wsUrl: string, config: any): string;
export interface BitfinexFeedConfig extends ExchangeFeedConfig {
standardMessages: boolean;
snapshotDepth?: number;
}
/**
* A client class exposing the Bitfinex public websocket feed
*
* The possible channels to subscribe to are: ticker, book, trades
*
* The raw feed is re-interpreted and emitted as POJOs rather than Bitfinex's array structures.
* If StandardMessages is true, the following standard messages are emitted
* ticker, snapshot, open, done, match
*
* The following events are emitted if standardMessages is false:
* bitfinex-ticker: BitfinexTickerMessage
* bitfinex-orderbook-snapshot: BitfinexOrderbookSnapshot
* bitfinex-orderbook-update: BitfinexOrderMessage
* bitfinex-trade-snapshot: BitfinexTradeSnapshot
* bitfinex-trade-update: BitfinexTradeMessage
*
* The following operational messages are also emitted
* close, error, open, connection
*
*/
export class BitfinexFeed extends ExchangeFeed {
constructor(config: BitfinexFeedConfig);
readonly owner: string;
clearChannels(): void;
/**
* Resubscribe to channels using fire-and-forget.
*/
resubscribeAll(): void;
subscribe(channelType: string, product: string): void;
unsubscribe(chanId: string): void;
onOpen(): void;
protected onClose(code: number, reason: string): void;
protected handleMessage(data: any): void;
}
export const GEMINI_API_URL = "https://api.gemini.com/v1";
export const GEMINI_WS_FEED = "wss://api.gemini.com/v1/marketdata/";
export class GeminiMarketFeed extends ExchangeFeed {
readonly owner: string;
readonly feedUrl: string;
static product(genericProduct: string): string;
static genericProduct(exchangeProduct: string): string;
static getMarket(genericProduct: string): any;
static getMarketForExchangeProduct(exchangeProduct: string): any;
constructor(config: GI.GeminiMarketFeedConfig);
protected getWebsocketUrlForProduct(product: string): string;
protected handleMessage(msg: string, productId?: string): void;
protected onOpen(): void;
}
export const BINANCE_WS_FEED: string;
export class BinanceFeed extends ExchangeFeed {
readonly owner: string;
readonly feedUrl: string;
protected lastHeartBeat: number;
protected initialMessagesQueue: {
[product: string]: BinanceMessage[];
};
protected depthsockets: {
[product: string]: WebSocket;
};
protected tradesockets: {
[product: string]: WebSocket;
};
constructor(config: GI.BinanceFeedConfig);
protected getWebsocketUrlForProduct(product: string): string;
protected connect(products?: string[]): Promise<void>;
subscribeProduct(product: string): Promise<void>;
protected handleMessage(): void;
protected handleSnapshotMessage(msg: BinanceSnapshotMessage, productId?: string): void;
protected handleTradeMessages(msg: string, productId?: string): void;
protected handleDepthMessages(msg: string, productId?: string): void;
nextSequence(prodcutId: string): number;
processLevelMessage(depthMessage: BinanceDepthMessage): void;
protected onOpen(): void;
}
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
export const GDAX_WS_FEED = "wss://ws-feed.gdax.com";
/**
* Configuration interface for a GDAX websocket feed stream. `wsUrl` is used to override the default websocket URL.
* Usually, you don't need this, but you may want to obtain a feed from the sandbox for testing, or an historical
* message source, for example.
*
* The channels array determines which types of messages are sent back down the feed. Leave this as null to receive
* all messages, or specify any of
* - `level2` - The orderbook messages
* - `matches` - aLl trades
* - `ticker` - Ticker updates (these come after every trade, so specifying both `matches` and `ticker` may be redundant)
* - `user` - If you provided auth credentials, private messages will also be sent
*/
export interface GDAXFeedConfig extends ExchangeFeedConfig {
auth: GDAXAuthConfig;
wsUrl: string;
channels: string[];
apiUrl: string;
}
/**
* The GDAX message feed. Messages are created via a combination of WS and REST calls, which are then sent down the pipe.
* It handles automatically reconnects on errors and tracks the connection by monitoring a heartbeat.
* You can create the feeds from here, but it's preferable to use the `getFeed` or `FeedFactory` functions to get a
* connection from the pool
*/
export class GDAXFeed extends ExchangeFeed {
constructor(config: GDAXFeedConfig);
readonly owner: string;
/**
* Returns the Authenticated API instance if auth credentials were supplied in the constructor; null otherwise
*/
readonly authenticatedAPI: AuthenticatedExchangeAPI;
/**
* Subscribe to the products given in the `products` array.
*
* `subscribe` returns a Promise that resolves to true if the subscription was successful.
*/
subscribe(products: string[]): Promise<boolean>;
protected onClose(code: number, reason: string): void;
protected validateAuth(auth: ExchangeAuthConfig): ExchangeAuthConfig;
/**
* Converts a GDAX feed message into a GTT [[StreamMessage]] instance
*/
protected handleMessage(msg: string): void;
protected onOpen(): void;
}
/***************************************************************************************************************************
* @license