Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bybit only spot #29

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,603 changes: 1,342 additions & 1,261 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@types/ws": "^8.5.3",
"async-genetic": "^1.6.8",
"binance-api-node": "0.11.29",
"bybit-api": "^3.8.2",
"cli-progress": "^3.11.2",
"nice-grpc": "^2.0.0",
"node-fetch": "^3.2.10",
Expand Down
100 changes: 100 additions & 0 deletions src/cli/tester/history-providers/bybit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { TimeFrame, Candle, InstrumentType } from '@debut/types';
import { convertTimeFrame } from '../../../transports/bybit';
import { DebutError, ErrorEnvironment } from '../../../modules/error';
import { date } from '@debut/plugin-utils';
import { APIResponseV3WithTime, CategorySymbolListV5, KlineIntervalV3, OHLCVKlineV5 } from 'bybit-api';

type GetKlineResponseType = APIResponseV3WithTime<CategorySymbolListV5<OHLCVKlineV5[], 'spot' | 'linear' | 'inverse'>>;

export function createRequestBybit(instrumentType: InstrumentType) {
let endpoint = 'api.bybit.com';
let apiName = 'api';
let apiVersion = 'v5';

if (instrumentType === 'FUTURES') {
// endpoint = 'fapi.binance.com';
// apiName = 'fapi';
// apiVersion = 'v1';
}

const apiBase = `https://${endpoint}/${apiVersion}`;

return async function requestBybit(
from: number,
to: number,
ticker: string,
interval: TimeFrame,
): Promise<Candle[]> {
const frameMs = date.intervalToMs(interval);
const frameMin = frameMs / 1000 / 60;
const binanceFrame: KlineIntervalV3 = convertTimeFrame(interval);
const isSameDay = date.isSameDay(new Date(from), new Date());

if (frameMin <= 60) {
const middleDay = from + 12 * 60 * 60 * 1000 - 1000;

/**
* Sometimes there can be a duplicate of the same candle,
* so common nu,ber of candles can be different for bybit and binances
* example:
* {time: 1707391800000, o: 2421.34, c: 2422.12, h: 2423.54, l: 2416.15, …}
* ---> {time: 1707392700000, o: 2422.12, c: 2425.11, h: 2425.77, l: 2418.8, …}
* ---> {time: 1707392700000, o: 2422.12, c: 2425.11, h: 2425.77, l: 2418.8, …}
* {time: 1707393600000, o: 2425.11, c: 2424.98, h: 2429.5, l: 2424.23, …}
*/
if (!isSameDay) {
to = to - frameMs;
}

const urlPart1 = `${apiBase}/market/kline?category=spot&symbol=${ticker}&interval=${binanceFrame}&start=${from}&end=${middleDay}&limit=720`;
const urlPart2 = `${apiBase}/market/kline?category=spot&symbol=${ticker}&interval=${binanceFrame}&start=${middleDay}&end=${to}&limit=720`;

const [req1, req2] = await Promise.all([
fetch(urlPart1).then((res) => res.json()),
middleDay < to ? fetch(urlPart2).then((res) => res.json()) : Promise.resolve({ result: { list: [] } }),
]);

const candles1: OHLCVKlineV5[] = req1?.result?.list?.length
? req1.result.list.sort((a: OHLCVKlineV5, b: OHLCVKlineV5) => +a[0] - +b[0])
: [];
const candles2: OHLCVKlineV5[] = req2?.result?.list?.length
? req2.result.list.sort((a: OHLCVKlineV5, b: OHLCVKlineV5) => +a[0] - +b[0])
: [];

return convertBybitTicks([...candles1, ...candles2]);
} else {
const url = `${apiBase}/market/kline?category=spot&symbol=${ticker}&interval=${binanceFrame}&start=${from}&end=${to}`;
const req1: GetKlineResponseType = await fetch(url)
.then((res) => res.json())
.then((data) => data.result.list.sort((a: OHLCVKlineV5, b: OHLCVKlineV5) => +a[0] - +b[0]));

let candles1: [] | OHLCVKlineV5[] = [];

if (req1?.result?.list?.length) {
candles1 = req1.result.list;
}

return convertBybitTicks(candles1);
}
};
}

function convertBybitTicks(data: OHLCVKlineV5[]) {
const ticks: Candle[] = [];
data.forEach((item) => {
const tick: Candle = {
time: +item[0],
o: parseFloat(item[1]),
c: parseFloat(item[4]),
h: parseFloat(item[2]),
l: parseFloat(item[3]),
v: parseFloat(item[5]),
};

if (tick.c) {
ticks.push(tick);
}
});

return ticks;
}
6 changes: 5 additions & 1 deletion src/cli/tester/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { SingleBar, Presets } from 'cli-progress';
import { DebutError, ErrorEnvironment } from '../../modules/error';
import { requestAlpaca } from './history-providers/alpaca';
import { createRequestBinance } from './history-providers/binance';
import { createRequestBybit } from './history-providers/bybit';
import { requestTinkoff } from './history-providers/tinkoff';

const DAY = 86400000;
export type RequestFn = (from: number, to: number, ticker: string, interval: TimeFrame) => Promise<Candle[]>;
export interface HistoryOptions {
broker: 'tinkoff' | 'binance' | 'alpaca';
broker: 'tinkoff' | 'binance' | 'alpaca' | 'bybit';
ticker: string;
instrumentType: InstrumentType;
days: number;
Expand All @@ -31,6 +32,9 @@ export async function getHistory(options: HistoryOptions): Promise<Candle[]> {
case 'binance':
requestFn = createRequestBinance(options.instrumentType);
break;
case 'bybit':
requestFn = createRequestBybit(options.instrumentType);
break;
case 'alpaca':
requestFn = requestAlpaca;
break;
Expand Down
2 changes: 2 additions & 0 deletions src/cli/tester/tester-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ export class TesterTransport implements BaseTransport {
switch (this.opts.broker) {
case 'binance':
return math.toFixed(lots, 4);
case 'bybit':
return math.toFixed(lots, 4);
case 'tinkoff':
default:
return Math.round(lots) || 1;
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { TinkoffTransport } from './transports/tinkoff';
export { BinanceTransport } from './transports/binance';
export { AlpacaTransport } from './transports/alpaca';
export { BybitTransport } from './transports/bybit';
export * from './cli/tester/history';
export { Debut } from './modules/debut';
Loading