Skip to content

Commit

Permalink
Update Auth feed for new API (coinbase#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
CjS77 authored Sep 21, 2017
1 parent 293a255 commit f592aa2
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 10 deletions.
6 changes: 6 additions & 0 deletions run-ts.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
BUILD=build
yarn run build
file=$1
jsfile=$BUILD/${file%ts}js
node $jsfile
3 changes: 1 addition & 2 deletions src/exchanges/gdax/GDAXExchangeAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import { PlaceOrderMessage } from '../../core/Messages';
import { Level3Order, LiveOrder } from '../../lib/Orderbook';
import request = require('superagent');
import querystring = require('querystring');
import Buffer = require('buffer');
import crypto = require('crypto');
import Response = request.Response;

Expand Down Expand Up @@ -326,7 +325,7 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
body = body || '';
const timestamp = (Date.now() / 1000).toFixed(3);
const what: string = timestamp + method + relativeURI + body;
const key = new Buffer.Buffer(this.auth.secret, 'base64');
const key = Buffer.from(this.auth.secret, 'base64');
const hmac = crypto.createHmac('sha256', key);
const signature = hmac.update(what).digest('base64');
return {
Expand Down
22 changes: 14 additions & 8 deletions src/exchanges/gdax/GDAXFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ import {
} from '../../core/Messages';
import { OrderPool } from '../../lib/BookBuilder';
import {
GDAXChangeMessage,
GDAXChangeMessage, GDAXChannel,
GDAXDoneMessage,
GDAXL2UpdateMessage,
GDAXMatchMessage,
GDAXMessage,
GDAXOpenMessage,
GDAXSnapshotMessage,
GDAXSnapshotMessage, GDAXSubscriptionsMessage,
GDAXTickerMessage
} from './GDAXMessages';
import { AuthenticatedExchangeAPI } from '../AuthenticatedExchangeAPI';
Expand Down Expand Up @@ -132,10 +132,6 @@ export class GDAXFeed extends ExchangeFeed {
this.emit('error', err);
return reject(err);
}
this.products = new Set<string>();
products.forEach((p) => {
this.products.add(p);
});
return resolve(true);
});
});
Expand Down Expand Up @@ -163,6 +159,9 @@ export class GDAXFeed extends ExchangeFeed {
const feedMessage: GDAXMessage = JSON.parse(msg);
let message: StreamMessage;
switch (feedMessage.type) {
case 'subscriptions':
this.setProducts(feedMessage as any);
return;
case 'heartbeat':
this.confirmAlive();
return;
Expand Down Expand Up @@ -209,7 +208,7 @@ export class GDAXFeed extends ExchangeFeed {
}

private signMessage(msg: any): any {
const headers: AuthHeaders = this.gdaxAPI.getSignature('GET', '/users/self', '');
const headers: AuthHeaders = this.gdaxAPI.getSignature('GET', '/users/self/verify', '');
msg.signature = headers['CB-ACCESS-SIGN'];
msg.key = headers['CB-ACCESS-KEY'];
msg.timestamp = headers['CB-ACCESS-TIMESTAMP'];
Expand Down Expand Up @@ -405,10 +404,10 @@ export class GDAXFeed extends ExchangeFeed {
* consideration
*/
private mapAuthMessage(feedMessage: GDAXMessage): StreamMessage {
const time = (feedMessage as any).time ? new Date((feedMessage as any).time) : new Date();
switch (feedMessage.type) {
case 'match':
const isTaker: boolean = !!(feedMessage as any).taker_user_id;
const time = (feedMessage as any).time ? new Date((feedMessage as any).time) : new Date();
let side: string;
if (!isTaker) {
side = (feedMessage as GDAXMatchMessage).side;
Expand Down Expand Up @@ -455,4 +454,11 @@ export class GDAXFeed extends ExchangeFeed {
} as UnknownMessage;
}
}

private setProducts(msg: GDAXSubscriptionsMessage) {
msg.channels.forEach((ch: GDAXChannel) => {
ch.product_ids.forEach((p: string) => this.products.add(p));
});
this.log('debug', 'GDAX Feed subscriptions confirmed', msg);
}
}
10 changes: 10 additions & 0 deletions src/exchanges/gdax/GDAXMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ export interface GDAXMessage {
user_id?: string; // Authenticated messages only
}

export interface GDAXChannel {
name: string;
product_ids: string[];
}

export interface GDAXSubscriptionsMessage {
type: string;
channels: GDAXChannel[];
}

export interface GDAXOpenMessage extends GDAXMessage {
sequence: number;
time: string;
Expand Down
42 changes: 42 additions & 0 deletions src/samples/gdaxAuthChannel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**********************************************************************************************************************
* @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. *
**********************************************************************************************************************/

import { GDAXFeed, GDAXFeedConfig } from '../exchanges/gdax/GDAXFeed';
import { ConsoleLoggerFactory } from '../utils/Logger';
import { getSubscribedFeeds } from '../factories/gdaxFactories';

const logger = ConsoleLoggerFactory();
const options: GDAXFeedConfig = {
logger: logger,
channels: ['matches', 'user'],
auth: {
key: process.env.GDAX_KEY,
secret: process.env.GDAX_SECRET,
passphrase: process.env.GDAX_PASSPHRASE
},
wsUrl: null,
apiUrl: null
};

if (!options.auth.key || !options.auth.secret) {
logger.log('error', 'API credentials are required for this demo');
process.exit(1);
}

getSubscribedFeeds(options, ['BTC-USD', 'LTC-USD']).then((feed: GDAXFeed) => {
feed.on('data', (msg: any) => {
const level = msg.type === 'match' ? 'debug' : 'info';
logger.log(level, `${msg.type} received`, msg);
});
});
8 changes: 8 additions & 0 deletions src/samples/gdaxDemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ gdax.loadAllOrders(product).then((orders) => {
total = total.plus(o.size);
});
console.log(`You have ${orders.length} orders on the book for a total of ${total.toFixed(1)} BTC`);
return gdax.handleResponse(gdax.authCall('GET', '/users/self', {}), {});
}).then((result) => {
console.log('Self');
console.log(JSON.stringify(result));
return gdax.handleResponse(gdax.authCall('GET', '/users/self/verify', {}), {});
}).then((result) => {
console.log('Self verify');
console.log(JSON.stringify(result));
}).catch(logError);

const order: PlaceOrderMessage = {
Expand Down

0 comments on commit f592aa2

Please sign in to comment.