Skip to content

Commit

Permalink
Merge branch 'master' into user-defined-type-guards
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 authored Apr 10, 2018
2 parents d953e7a + 66a5093 commit 8b2e5da
Show file tree
Hide file tree
Showing 33 changed files with 250 additions and 190 deletions.
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ node_modules/
!types/
docs/apiref

src/
/src/
npm-shrinkwrap.json
yarn.lock
tsconfig.json
10 changes: 4 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@
"@types/query-string": "3.0.30",
"@types/simple-mock": "0.0.27",
"@types/superagent": "2.0.35",
"@types/uuid": "2.0.29",
"@types/winston": "2.2.0",
"@types/winston": "2.3.8",
"@types/ws": "0.0.37",
"bignumber.js": "4.0.2",
"bintrees": "1.0.1",
Expand All @@ -72,11 +71,10 @@
"nock": "9.0.2",
"nyc": "11.1.0",
"source-map-support": "0.4.16",
"ts-node": "^3.3.0",
"tslint": "5.6.0",
"ts-node": "^5.0.1",
"tslint": "^5.9.1",
"typedoc": "0.8.0",
"typescript": "^2.5.3",
"uuid": "3.0.0"
"typescript": "^2.7.2"
},
"resolutions": {
"deasync": "^0.1.12"
Expand Down
8 changes: 5 additions & 3 deletions src/consoles/gdaxConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import { Ticker } from '../exchanges/PublicExchangeAPI';
import { Balances } from '../exchanges/AuthenticatedExchangeAPI';
import { PlaceOrderMessage } from '../core/Messages';
import { LiveOrder } from '../lib/Orderbook';
import { AuthCallOptions, GDAXAuthConfig, GDAXConfig } from '../exchanges/gdax/GDAXInterfaces';
import { AuthCallOptions,
GDAXAuthConfig,
GDAXConfig } from '../exchanges/gdax/GDAXInterfaces';
import { TransferRequest, TransferResult } from '../exchanges/ExchangeTransferAPI';
import { Big } from '../lib/types';

Expand Down Expand Up @@ -142,11 +144,11 @@ if (program.newMarketOrder && hasAuth()) {
}
const vals = program.newMarketOrder.split(',');
const params: PlaceOrderMessage = {
type: 'placeOrder',
time: new Date(),
clientId: null,
side: vals[0],
size: vals[1],
type: 'market',
productId: program.product,
price: null,
orderType: 'market'
Expand All @@ -165,11 +167,11 @@ if (program.newLimitOrder && hasAuth()) {
}
const [side, size, price] = program.newLimitOrder.split(',');
const params: PlaceOrderMessage = {
type: 'placeOrder',
time: new Date(),
clientId: null,
side: side,
size: size,
type: 'market',
productId: program.product,
price: price,
orderType: 'limit'
Expand Down
3 changes: 2 additions & 1 deletion src/core/ExchangeRateFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/

import { AbstractMessageTransform, MessageTransformConfig } from '../lib/AbstractMessageTransform';
import { AbstractMessageTransform,
MessageTransformConfig } from '../lib/AbstractMessageTransform';
import { StreamMessage } from './Messages';
import { CurrencyPair, FXObject, pairAsString } from '../FXService/FXProvider';
import { FXRates, FXService } from '../FXService/FXService';
Expand Down
7 changes: 6 additions & 1 deletion src/core/HFTFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/

import { BaseOrderMessage, ChangedOrderMessage, isBaseOrderMessage, isStreamMessage, NewOrderMessage, StreamMessage } from './Messages';
import { BaseOrderMessage,
ChangedOrderMessage,
isBaseOrderMessage,
isStreamMessage,
NewOrderMessage,
StreamMessage } from './Messages';
import { RBTree } from 'bintrees';
import { Duplex } from 'stream';
import { MessageTransformConfig } from '../lib/AbstractMessageTransform';
Expand Down
13 changes: 9 additions & 4 deletions src/core/LiveOrderbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,14 @@
***************************************************************************************************************************/

import { Big, BigJS, Biglike, ZERO } from '../lib/types';
import { CumulativePriceLevel, Level3Order, Orderbook, OrderbookState } from '../lib/Orderbook';
import { AggregatedLevelFactory, AggregatedLevelWithOrders, BookBuilder, StartPoint } from '../lib/BookBuilder';
import { CumulativePriceLevel,
Level3Order,
Orderbook,
OrderbookState } from '../lib/Orderbook';
import { AggregatedLevelFactory,
AggregatedLevelWithOrders,
BookBuilder,
StartPoint } from '../lib/BookBuilder';
import { Logger } from '../utils/Logger';
import { Ticker } from '../exchanges/PublicExchangeAPI';
import {
Expand Down Expand Up @@ -292,8 +298,7 @@ export class LiveOrderbook extends Duplex implements Orderbook {
// If we're using an order pool, then we only remove orders that we're aware of. GDAX, for example might
// send a done message for a stop order that is cancelled (and was not previously known to us).
// Also filled orders will already have been removed by the time a GDAX done order reaches here
const book: BookBuilder = this._book;
if (!book.hasOrder(msg.orderId)) {
if (!this._book.hasOrder(msg.orderId)) {
return;
}
if (!(this._book.remove(msg.orderId))) {
Expand Down
2 changes: 1 addition & 1 deletion src/core/MessageQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { Duplex } from 'stream';
*
* @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
* @param product {string} A product to filter for. A single feed might be producing messages from 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
Expand Down
7 changes: 6 additions & 1 deletion src/core/Messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export function isErrorMessage(msg: any): msg is ErrorMessage {
* Any context-rich information can be extracted into the `extra` field, and the original message should be attached to the `origin` field as usual.
*/
export interface UnknownMessage extends StreamMessage {
type: 'unknown';
sequence?: number;
productId?: string;
tag?: string;
Expand Down Expand Up @@ -179,6 +180,7 @@ export interface TickerMessage extends StreamMessage, Ticker {
* in the extra field, which can be handled by the target trade engine.
*/
export interface PlaceOrderMessage extends StreamMessage {
type: 'placeOrder';
productId: string;
clientId?: string;
side: string;
Expand All @@ -191,14 +193,15 @@ export interface PlaceOrderMessage extends StreamMessage {
}

export interface CancelOrderRequestMessage extends StreamMessage {
type: string; // cancelOrder
type: 'cancelOrder';
orderId: string;
}

/**
* Emitted from a feed when one of my orders has been matched. (An authenticated feed is required)
*/
export interface TradeExecutedMessage extends StreamMessage {
type: 'tradeExecuted';
productId: string;
orderId: string;
side: string;
Expand All @@ -209,6 +212,7 @@ export interface TradeExecutedMessage extends StreamMessage {
}

export interface TradeFinalizedMessage extends StreamMessage {
type: 'tradeFinalized';
productId: string;
orderId: string;
side: string;
Expand All @@ -218,6 +222,7 @@ export interface TradeFinalizedMessage extends StreamMessage {
}

export interface MyOrderPlacedMessage extends StreamMessage {
type: 'myOrderPlaced';
productId: string;
orderId: string;
side: string;
Expand Down
8 changes: 5 additions & 3 deletions src/core/ProductFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/

import { AbstractMessageTransform, MessageTransformConfig } from '../lib/AbstractMessageTransform';
import { AbstractMessageTransform,
MessageTransformConfig } from '../lib/AbstractMessageTransform';
import { StreamMessage } from '../core/Messages';

export interface ProductFilterConfig extends MessageTransformConfig {
productId: string;
Expand All @@ -29,8 +31,8 @@ export class ProductFilter extends AbstractMessageTransform {
this.productId = config.productId;
}

transformMessage(msg: any): any {
if (!msg || !msg.productId || msg.productId !== this.productId) {
transformMessage(msg: StreamMessage): StreamMessage {
if (!msg || !(msg as any).productId || (msg as any).productId !== this.productId) {
return null;
}
return msg;
Expand Down
25 changes: 15 additions & 10 deletions src/core/Trader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ import { Logger } from '../utils/Logger';
import { AuthenticatedExchangeAPI } from '../exchanges/AuthenticatedExchangeAPI';
import { BookBuilder } from '../lib/BookBuilder';
import { Level3Order, LiveOrder, OrderbookState } from '../lib/Orderbook';
import { CancelOrderRequestMessage, isStreamMessage, MyOrderPlacedMessage, PlaceOrderMessage, StreamMessage, TradeExecutedMessage, TradeFinalizedMessage } from './Messages';
import { CancelOrderRequestMessage,
isStreamMessage,
MyOrderPlacedMessage,
PlaceOrderMessage,
StreamMessage,
TradeExecutedMessage,
TradeFinalizedMessage } from './Messages';
import { OrderbookDiff } from '../lib/OrderbookDiff';
import { Big, BigJS } from '../lib/types';
import { StreamError } from '../lib/errors';
Expand Down Expand Up @@ -104,15 +110,14 @@ export class Trader extends Writable {
// We pass the message along, but let the user decide what to do
// We also have to wrap this call in a setImmediate; else any errors in the event handler will get thrown from here and lead to an unhandledRejection
this.emitMessageAsync('Trader.place-order-failed', err.asMessage());
return Promise.resolve(null);
return null;
});
}

cancelOrder(orderId: string): Promise<string> {
return this.api.cancelOrder(orderId).then((id: string) => {
// To avoid race conditions, we only actually remove the order when the tradeFinalized message arrives
return id;
});
// To avoid race conditions, we only actually remove the order
// when the tradeFinalized message arrives.
return this.api.cancelOrder(orderId);
}

cancelMyOrders(): Promise<string[]> {
Expand Down Expand Up @@ -159,8 +164,7 @@ export class Trader extends Writable {
actualOrders.forEach((order: LiveOrder) => {
book.add(order);
});
const diff = OrderbookDiff.compareByOrder(this.myBook, book);
return Promise.resolve(diff);
return OrderbookDiff.compareByOrder(this.myBook, book);
});
}

Expand Down Expand Up @@ -211,7 +215,7 @@ export class Trader extends Writable {

private handleCancelOrder(request: CancelOrderRequestMessage) {
this.cancelOrder(request.orderId).then((result: string) => {
return this.emitMessageAsync('Trader.order-cancelled', result);
this.emitMessageAsync('Trader.order-cancelled', result);
}, (err: Error) => {
this.emitMessageAsync('Trader.cancel-order-failed', err);
});
Expand All @@ -228,7 +232,8 @@ export class Trader extends Writable {
const order: Level3Order = this.myBook.getOrder(msg.orderId);
if (!order) {
this.logger.log('warn', 'Traded order not in my book', msg);
this.emit('Trader.outOfSyncWarning', 'Traded order not in my book');
this.emit('Trader.outOfSyncWarning',
`Traded order ${msg.orderId} not in my book`);
return;
}
let newSize: BigJS;
Expand Down
6 changes: 5 additions & 1 deletion src/exchanges/AuthenticatedExchangeAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ export interface AvailableBalance {
available: BigJS;
}

export interface AvailableBalances {
[currency: string]: AvailableBalance;
}

export interface Balances {
[profileId: string]: { [currency: string]: AvailableBalance };
[profileId: string]: AvailableBalances;
}
2 changes: 1 addition & 1 deletion src/exchanges/ExchangeFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { sanitizeMessage } from '../core/Messages';
export class ExchangeFeedConfig {
wsUrl: string;
logger: Logger;
auth: ExchangeAuthConfig;
auth?: ExchangeAuthConfig;
}

// hooks for replacing libraries if desired
Expand Down
4 changes: 2 additions & 2 deletions src/exchanges/ccxt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { Candle, CandleRequestOptions, Product, PublicExchangeAPI, Ticker } from
import { AuthenticatedExchangeAPI, Balances } from '../AuthenticatedExchangeAPI';
import { CryptoAddress, ExchangeTransferAPI, TransferRequest, TransferResult, WithdrawalRequest } from '../ExchangeTransferAPI';
import { ExchangeAuthConfig } from '../AuthConfig';
import { Big, BigJS } from '../../lib/types';
import { Big, BigJS, ZERO } from '../../lib/types';
import { BookBuilder } from '../../lib/BookBuilder';
import { PlaceOrderMessage, TradeMessage } from '../../core/Messages';
import { Level3Order, LiveOrder } from '../../lib/Orderbook';
Expand Down Expand Up @@ -235,7 +235,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
}
const t: Ticker = {
productId: gdaxProduct,
price: Big(0),
price: ZERO,
time: new Date(ticker.timestamp),
ask: Big(ticker.bid),
bid: Big(ticker.ask),
Expand Down
9 changes: 3 additions & 6 deletions src/exchanges/gdax/GDAXExchangeAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,7 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
return Promise.reject(new GTTError('Invalid Order type: ' + order.type));
}

// TODO: use this.authClient.placeOrder() when gdax's
// index.d.ts adds it.
const promise = side === 'buy' ? this.authClient.buy(gdaxOrder) : this.authClient.sell(gdaxOrder);
return promise.then((result: OrderResult) => {
return this.authClient.placeOrder(gdaxOrder).then((result: OrderResult) => {
// Check for error
// TODO: Remove the first type assertion when https://github.com/coinbase/gdax-node/issues/269 is fixed.
if ((result as any).status === 'rejected' || (result as any).message) {
Expand Down Expand Up @@ -376,9 +373,9 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
});
}

checkAuth(): Promise<GDAXAuthConfig> {
checkAuth(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.auth === null) {
if (!this.auth) {
return reject(new GTTError('You cannot make authenticated requests if a GDAXAuthConfig object was not provided to the GDAXExchangeAPI constructor'));
}
if (!(this.auth.key && this.auth.secret && this.auth.passphrase)) {
Expand Down
Loading

0 comments on commit 8b2e5da

Please sign in to comment.