Skip to content

Commit

Permalink
add caching to coincheck position retrival
Browse files Browse the repository at this point in the history
  • Loading branch information
bitrinjani committed Dec 18, 2017
1 parent e30c193 commit 861d7f0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Coincheck/BrokerApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import {
LeveragePosition, OrderBooksResponse, NewOrderRequest, NewOrderResponse,
CancelOrderResponse, OpenOrdersResponse, TransactionsResponse, Pagination, Transaction, LeverageBalanceResponse
} from './types';
import { setTimeout } from 'timers';

export default class BrokerApi {
private static CACHE_MS = 50;
private leveragePositionsCache?: LeveragePosition[];
private readonly baseUrl = 'https://coincheck.com';
private readonly webClient: WebClient = new WebClient(this.baseUrl);

Expand Down Expand Up @@ -36,6 +39,9 @@ export default class BrokerApi {
}

async getAllOpenLeveragePositions(limit: number = 20): Promise<LeveragePosition[]> {
if (this.leveragePositionsCache) {
return _.cloneDeep(this.leveragePositionsCache);
}
let result: LeveragePosition[] = [];
const request: LeveragePositionsRequest = { limit, status: 'open', order: 'desc' };
let reply = await this.getLeveragePositions(request);
Expand All @@ -45,6 +51,8 @@ export default class BrokerApi {
const last = _.last(reply.data) as LeveragePosition;
reply = await this.getLeveragePositions({ ...request, starting_after: last.id });
}
this.leveragePositionsCache = result;
setTimeout(() => this.leveragePositionsCache = undefined, BrokerApi.CACHE_MS);
return result;
}

Expand Down
10 changes: 10 additions & 0 deletions src/__tests__/Coincheck/BrokerApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ describe('BrokerApi', () => {
expect(positions[1].new_order.created_at.toISOString()).toBe('2017-10-20T22:41:59.000Z');
});

test('getAllOpenLeveragePositions cache', async () => {
const api = new BrokerApi('', '');
let positions = await api.getAllOpenLeveragePositions(4);
expect(positions.length).toBe(9);
expect(positions[1].new_order.created_at.toISOString()).toBe('2017-10-20T22:41:59.000Z');
positions = await api.getAllOpenLeveragePositions(4);
expect(positions.length).toBe(9);
expect(positions[1].new_order.created_at.toISOString()).toBe('2017-10-20T22:41:59.000Z');
});

test('getOrderBooks', async () => {
const api = new BrokerApi('', '');
const orderBooks = await api.getOrderBooks();
Expand Down

0 comments on commit 861d7f0

Please sign in to comment.