Skip to content

Commit

Permalink
Borrow rate types and parsers (#22205)
Browse files Browse the repository at this point in the history
* chore: new type IsolatedBorrowRate

* refactor: changed BorrowRate type to CrossBorrowRate

* feat(base/exchange): parseIsolatedBorrowRates, parseIsolatedBorrowRate

* feat: new types - CrossBorrowRate, IsolatedBorrowRate

* fetchCrossBorrowRate(s) return type

* fetch(Cross|Isolated)BorrowRate(s) return types

* base/Exchange import CrossBorrowRate

* Exchange.ts removed BorrowRate type

* types.py linting

* fix crossborrowRates transpiling

* bybit minor fix

---------

Co-authored-by: carlosmiei <[email protected]>
  • Loading branch information
samgermain and carlosmiei committed Apr 28, 2024
1 parent dcd92ad commit b0ce488
Show file tree
Hide file tree
Showing 13 changed files with 215 additions and 61 deletions.
7 changes: 5 additions & 2 deletions build/transpile.js
Expand Up @@ -994,13 +994,16 @@ class Transpiler {
'Balances': /-> Balances:/,
'Bool': /: Bool =/,
'Conversion': /-> Conversion:/,
'CrossBorrowRate': /-> CrossBorrowRate:/,
'CrossBorrowRates': /-> CrossBorrowRates:/,
'Currencies': /-> Currencies:/,
'Currency': /(-> Currency:|: Currency)/,
'FundingHistory': /\[FundingHistory/,
'Greeks': /-> Greeks:/,
'IndexType': /: IndexType/,
'Int': /: Int =/,
'Liquidation': /-> (?:List\[)?Liquidation/,
'IsolatedBorrowRate': /-> IsolatedBorrowRate:/,
'IsolatedBorrowRates': /-> IsolatedBorrowRates:/,
'LastPrice': /-> LastPrice:/,
'LastPrices': /-> LastPrices:/,
'Leverage': /-> Leverage:/,
Expand Down Expand Up @@ -1683,7 +1686,7 @@ class Transpiler {
'Dictionary<any>': 'array',
'Dict': 'array',
}
const phpArrayRegex = /^(?:Market|Currency|Account|AccountStructure|BalanceAccount|object|OHLCV|Order|OrderBook|Tickers?|Trade|Transaction|Balances?|MarketInterface|TransferEntry|Leverages|Leverage|Greeks|MarginModes|MarginMode|MarginModification|LastPrice|LastPrices|TradingFeeInterface|Currencies|TradingFees)( \| undefined)?$|\w+\[\]/
const phpArrayRegex = /^(?:Market|Currency|Account|AccountStructure|BalanceAccount|object|OHLCV|Order|OrderBook|Tickers?|Trade|Transaction|Balances?|MarketInterface|TransferEntry|Leverages|Leverage|Greeks|MarginModes|MarginMode|MarginModification|LastPrice|LastPrices|TradingFeeInterface|Currencies|TradingFees|CrossBorrowRate|IsolatedBorrowRate)( \| undefined)?$|\w+\[\]/
let phpArgs = args.map (x => {
const parts = x.split (':')
if (parts.length === 1) {
Expand Down
122 changes: 114 additions & 8 deletions cs/ccxt/base/Exchange.Types.cs
Expand Up @@ -758,25 +758,131 @@ public DepositAddressResponse(object depositAddressResponse2)
}
}

public struct BorrowRate
public struct CrossBorrowRate
{
public string? currency;
public double? rate;
public Int64? timestamp;
public string? datetime;
public Dictionary<string, object> info;

public BorrowRate(object borrowRate)
public CrossBorrowRate(object crossBorrowRate)
{
var borrowRate2 = (Dictionary<string, object>)borrowRate;
currency = Exchange.SafeString(borrowRate2, "currency");
rate = Exchange.SafeFloat(borrowRate2, "rate");
timestamp = Exchange.SafeInteger(borrowRate2, "timestamp");
datetime = Exchange.SafeString(borrowRate2, "datetime");
info = borrowRate2.ContainsKey("info") ? (Dictionary<string, object>)borrowRate2["info"] : null;
var crossBorrowRate2 = (Dictionary<string, object>)crossBorrowRate;
currency = Exchange.SafeString(crossBorrowRate2, "currency");
rate = Exchange.SafeFloat(crossBorrowRate2, "rate");
timestamp = Exchange.SafeInteger(crossBorrowRate2, "timestamp");
datetime = Exchange.SafeString(crossBorrowRate2, "datetime");
info = crossBorrowRate2.ContainsKey("info") ? (Dictionary<string, object>)crossBorrowRate2["info"] : null;
}
}

public struct CrossBorrowRates
{
public Dictionary<string, object> info;
public Dictionary<string, CrossBorrowRate> crossBorrowRates;

public CrossBorrowRates(object crossBorrowRates2)
{
var crossBorrowRates = (Dictionary<string, object>)crossBorrowRates2;

info = crossBorrowRates.ContainsKey("info") ? (Dictionary<string, object>)crossBorrowRates["info"] : null;
this.crossBorrowRates = new Dictionary<string, CrossBorrowRate>();
foreach (var crossBorrowRate in crossBorrowRates)
{
if (crossBorrowRate.Key != "info")
this.crossBorrowRates.Add(crossBorrowRate.Key, new CrossBorrowRate(crossBorrowRate.Value));
}
}

// Indexer
public CrossBorrowRate this[string key]
{
get
{
if (crossBorrowRates.ContainsKey(key))
{
return crossBorrowRates[key];
}
else
{
throw new KeyNotFoundException($"The key '{key}' was not found in the isolatedBorrowRates.");
}
}
set
{
crossBorrowRates[key] = value;
}
}
}

public struct IsolatedBorrowRate
{
public string symbol;
// public string base;
public double? baseRate;
public string quote;
public double? quoteRate;
public double? rate;
public Int64? timestamp;
public string? datetime;
public Dictionary<string, object> info;

public IsolatedBorrowRate(object isolatedBorrowRate)
{
var isolatedBorrowRate2 = (Dictionary<string, object>)isolatedBorrowRate;
symbol = Exchange.SafeString (isolatedBorrowRate2, "symbol");
// base = Exchange.SafeString (isolatedBorrowRate2, "base");
baseRate = Exchange.SafeFloat (isolatedBorrowRate2, "baseRate");
quote = Exchange.SafeString (isolatedBorrowRate2, "quote");
quoteRate = Exchange.SafeFloat (isolatedBorrowRate2, "quoteRate");
rate = Exchange.SafeFloat(isolatedBorrowRate2, "rate");
timestamp = Exchange.SafeInteger(isolatedBorrowRate2, "timestamp");
datetime = Exchange.SafeString(isolatedBorrowRate2, "datetime");
info = isolatedBorrowRate2.ContainsKey("info") ? (Dictionary<string, object>)isolatedBorrowRate2["info"] : null;
}
}

public struct IsolatedBorrowRates
{
public Dictionary<string, object> info;
public Dictionary<string, IsolatedBorrowRate> isolatedBorrowRates;

public IsolatedBorrowRates(object isolatedBorrowRates2)
{
var isolatedBorrowRates = (Dictionary<string, object>)isolatedBorrowRates2;

info = isolatedBorrowRates.ContainsKey("info") ? (Dictionary<string, object>)isolatedBorrowRates["info"] : null;
this.isolatedBorrowRates = new Dictionary<string, IsolatedBorrowRate>();
foreach (var isolatedBorrowRate in isolatedBorrowRates)
{
if (isolatedBorrowRate.Key != "info")
this.isolatedBorrowRates.Add(isolatedBorrowRate.Key, new IsolatedBorrowRate(isolatedBorrowRate.Value));
}
}

// Indexer
public IsolatedBorrowRate this[string key]
{
get
{
if (isolatedBorrowRates.ContainsKey(key))
{
return isolatedBorrowRates[key];
}
else
{
throw new KeyNotFoundException($"The key '{key}' was not found in the isolatedBorrowRates.");
}
}
set
{
isolatedBorrowRates[key] = value;
}
}
}


public struct BorrowInterest
{
public string? account;
Expand Down
25 changes: 25 additions & 0 deletions python/ccxt/base/types.py
Expand Up @@ -148,11 +148,13 @@ class OrderRequest(TypedDict):
price: Union[None, float]
params: Dict[str, Any]


class CancellationRequest(TypedDict):
id: Str
symbol: Str
clientOrderId: Str


class Order(TypedDict):
info: Dict[str, Any]
id: Str
Expand Down Expand Up @@ -437,9 +439,32 @@ class MarginModification(TypedDict):
datetime: Str


class CrossBorrowRate(TypedDict):
info: Dict[str, any]
currency: Str
rate: float
period: Optional[float]
timestamp: Int
datetime: Str


class IsolatedBorrowRate(TypedDict):
info: Dict[str, any]
symbol: str
base: str
baseRate: float
quote: str
quoteRate: float
period: Int
timestamp: Int
datetime: Str


LastPrices = Dict[Str, LastPrice]
Currencies = Dict[Str, CurrencyInterface]
TradingFees = Dict[Str, TradingFeeInterface]
IsolatedBorrowRates = Dict[Str, IsolatedBorrowRate]
CrossBorrowRates = Dict[Str, CrossBorrowRate]

Market = Optional[MarketInterface]
Currency = Optional[CurrencyInterface]
29 changes: 22 additions & 7 deletions ts/src/base/Exchange.ts
Expand Up @@ -146,10 +146,10 @@ import { OrderBook as WsOrderBook, IndexedOrderBook, CountedOrderBook } from './
//
import { axolotl } from './functions/crypto.js';
// import types
import type { Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, FundingRate, DepositWithdrawFeeNetwork, LedgerEntry, BorrowInterest, OpenInterest, LeverageTier, TransferEntry, BorrowRate, FundingRateHistory, Liquidation, FundingHistory, OrderRequest, MarginMode, Tickers, Greeks, Option, OptionChain, Str, Num, MarketInterface, CurrencyInterface, BalanceAccount, MarginModes, MarketType, Leverage, Leverages, LastPrice, LastPrices, Account, Strings, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion, CancellationRequest } from './types.js';
import type { Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, FundingRate, DepositWithdrawFeeNetwork, LedgerEntry, BorrowInterest, OpenInterest, LeverageTier, TransferEntry, FundingRateHistory, Liquidation, FundingHistory, OrderRequest, MarginMode, Tickers, Greeks, Option, OptionChain, Str, Num, MarketInterface, CurrencyInterface, BalanceAccount, MarginModes, MarketType, Leverage, Leverages, LastPrice, LastPrices, Account, Strings, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion, CancellationRequest, IsolatedBorrowRate, IsolatedBorrowRates, CrossBorrowRates, CrossBorrowRate } from './types.js';
// export {Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, FundingRateHistory, Liquidation, FundingHistory} from './types.js'
// import { Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, FundingRateHistory, OpenInterest, Liquidation, OrderRequest, FundingHistory, MarginMode, Tickers, Greeks, Str, Num, MarketInterface, CurrencyInterface, Account } from './types.js';
export type { Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, LedgerEntry, BorrowInterest, OpenInterest, LeverageTier, TransferEntry, BorrowRate, FundingRateHistory, Liquidation, FundingHistory, OrderRequest, MarginMode, Tickers, Greeks, Option, OptionChain, Str, Num, MarketInterface, CurrencyInterface, BalanceAccount, MarginModes, MarketType, Leverage, Leverages, LastPrice, LastPrices, Account, Strings, Conversion } from './types.js'
export type { Market, Trade, Fee, Ticker, OHLCV, OHLCVC, Order, OrderBook, Balance, Balances, Dictionary, Transaction, DepositAddressResponse, Currency, MinMax, IndexType, Int, OrderType, OrderSide, Position, LedgerEntry, BorrowInterest, OpenInterest, LeverageTier, TransferEntry, CrossBorrowRate, FundingRateHistory, Liquidation, FundingHistory, OrderRequest, MarginMode, Tickers, Greeks, Option, OptionChain, Str, Num, MarketInterface, CurrencyInterface, BalanceAccount, MarginModes, MarketType, Leverage, Leverages, LastPrice, LastPrices, Account, Strings, Conversion } from './types.js'

// ----------------------------------------------------------------------------
// move this elsewhere.
Expand Down Expand Up @@ -2337,11 +2337,11 @@ export default class Exchange {
throw new NotSupported (this.id + ' parseOrder() is not supported yet');
}

async fetchCrossBorrowRates (params = {}): Promise<{}> {
async fetchCrossBorrowRates (params = {}): Promise<CrossBorrowRates> {
throw new NotSupported (this.id + ' fetchCrossBorrowRates() is not supported yet');
}

async fetchIsolatedBorrowRates (params = {}): Promise<{}> {
async fetchIsolatedBorrowRates (params = {}): Promise<IsolatedBorrowRates> {
throw new NotSupported (this.id + ' fetchIsolatedBorrowRates() is not supported yet');
}

Expand All @@ -2365,6 +2365,10 @@ export default class Exchange {
throw new NotSupported (this.id + ' parseBorrowInterest() is not supported yet');
}

parseIsolatedBorrowRate (info, market: Market = undefined): IsolatedBorrowRate {
throw new NotSupported (this.id + ' parseIsolatedBorrowRate() is not supported yet');
}

parseWsTrade (trade, market: Market = undefined): Trade {
throw new NotSupported (this.id + ' parseWsTrade() is not supported yet');
}
Expand Down Expand Up @@ -4455,7 +4459,7 @@ export default class Exchange {
}
}

async fetchCrossBorrowRate (code: string, params = {}): Promise<{}> {
async fetchCrossBorrowRate (code: string, params = {}): Promise<CrossBorrowRate> {
await this.loadMarkets ();
if (!this.has['fetchBorrowRates']) {
throw new NotSupported (this.id + ' fetchCrossBorrowRate() is not supported yet');
Expand All @@ -4468,13 +4472,13 @@ export default class Exchange {
return rate;
}

async fetchIsolatedBorrowRate (symbol: string, params = {}): Promise<{}> {
async fetchIsolatedBorrowRate (symbol: string, params = {}): Promise<IsolatedBorrowRate> {
await this.loadMarkets ();
if (!this.has['fetchBorrowRates']) {
throw new NotSupported (this.id + ' fetchIsolatedBorrowRate() is not supported yet');
}
const borrowRates = await this.fetchIsolatedBorrowRates (params);
const rate = this.safeDict (borrowRates, symbol);
const rate = this.safeDict (borrowRates, symbol) as IsolatedBorrowRate;
if (rate === undefined) {
throw new ExchangeError (this.id + ' fetchIsolatedBorrowRate() could not find the borrow rate for market symbol ' + symbol);
}
Expand Down Expand Up @@ -5834,6 +5838,17 @@ export default class Exchange {
return interests;
}

parseIsolatedBorrowRates (info: any): IsolatedBorrowRates {
const result = {};
for (let i = 0; i < info.length; i++) {
const item = info[i];
const borrowRate = this.parseIsolatedBorrowRate (item);
const symbol = this.safeString (borrowRate, 'symbol');
result[symbol] = borrowRate;
}
return result as any;
}

parseFundingRateHistories (response, market = undefined, since: Int = undefined, limit: Int = undefined): FundingRateHistory[] {
const rates = [];
for (let i = 0; i < response.length; i++) {
Expand Down
24 changes: 21 additions & 3 deletions ts/src/base/types.ts
Expand Up @@ -389,13 +389,25 @@ export interface TransferEntry {
status?: Str;
}

export interface BorrowRate {
export interface CrossBorrowRate {
info: any;
currency?: Str;
rate?: number;
rate: number;
period?: number;
timestamp?: number;
datetime?: Str;
info: any;
}

export interface IsolatedBorrowRate {
info: any,
symbol: string,
base: string,
baseRate: number,
quote: string,
quoteRate: number,
period?: Int,
timestamp?: Int,
datetime?: Str,
}

export interface FundingRateHistory {
Expand Down Expand Up @@ -560,6 +572,12 @@ export interface MarginModes extends Dictionary<MarginMode> {
export interface OptionChain extends Dictionary<Option> {
}

export interface IsolatedBorrowRates extends Dictionary<IsolatedBorrowRates> {
}

export interface CrossBorrowRates extends Dictionary<CrossBorrowRates> {
}

/** [ timestamp, open, high, low, close, volume ] */
export type OHLCV = [Num, Num, Num, Num, Num, Num];

Expand Down
4 changes: 2 additions & 2 deletions ts/src/binance.ts
Expand Up @@ -4,7 +4,7 @@
import Exchange from './abstract/binance.js';
import { ExchangeError, ArgumentsRequired, OperationFailed, OperationRejected, InsufficientFunds, OrderNotFound, InvalidOrder, DDoSProtection, InvalidNonce, AuthenticationError, RateLimitExceeded, PermissionDenied, NotSupported, BadRequest, BadSymbol, AccountSuspended, OrderImmediatelyFillable, OnMaintenance, BadResponse, RequestTimeout, OrderNotFillable, MarginModeAlreadySet } from './base/errors.js';
import { Precise } from './base/Precise.js';
import type { TransferEntry, Int, OrderSide, Balances, OrderType, Trade, OHLCV, Order, FundingRateHistory, OpenInterest, Liquidation, OrderRequest, Str, Transaction, Ticker, OrderBook, Tickers, Market, Greeks, Strings, Currency, MarketInterface, MarginMode, MarginModes, Leverage, Leverages, Num, Option, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion } from './base/types.js';
import type { TransferEntry, Int, OrderSide, Balances, OrderType, Trade, OHLCV, Order, FundingRateHistory, OpenInterest, Liquidation, OrderRequest, Str, Transaction, Ticker, OrderBook, Tickers, Market, Greeks, Strings, Currency, MarketInterface, MarginMode, MarginModes, Leverage, Leverages, Num, Option, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion, CrossBorrowRate } from './base/types.js';
import { TRUNCATE, DECIMAL_PLACES } from './base/functions/number.js';
import { sha256 } from './static_dependencies/noble-hashes/sha256.js';
import { rsa } from './base/functions/rsa.js';
Expand Down Expand Up @@ -11133,7 +11133,7 @@ export default class binance extends Exchange {
return await this.modifyMarginHelper (symbol, amount, 1, params);
}

async fetchCrossBorrowRate (code: string, params = {}) {
async fetchCrossBorrowRate (code: string, params = {}): Promise<CrossBorrowRate> {
/**
* @method
* @name binance#fetchCrossBorrowRate
Expand Down
8 changes: 4 additions & 4 deletions ts/src/bitget.ts
Expand Up @@ -6,7 +6,7 @@ import { ExchangeError, ExchangeNotAvailable, NotSupported, OnMaintenance, Argum
import { Precise } from './base/Precise.js';
import { TICK_SIZE } from './base/functions/number.js';
import { sha256 } from './static_dependencies/noble-hashes/sha256.js';
import type { Int, OrderSide, OrderType, Trade, OHLCV, Order, FundingRateHistory, OrderRequest, FundingHistory, Balances, Str, Transaction, Ticker, OrderBook, Tickers, Market, Strings, Currency, Position, Liquidation, TransferEntry, Leverage, MarginMode, Num, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion } from './base/types.js';
import type { Int, OrderSide, OrderType, Trade, OHLCV, Order, FundingRateHistory, OrderRequest, FundingHistory, Balances, Str, Transaction, Ticker, OrderBook, Tickers, Market, Strings, Currency, Position, Liquidation, TransferEntry, Leverage, MarginMode, Num, MarginModification, TradingFeeInterface, Currencies, TradingFees, Conversion, CrossBorrowRate, IsolatedBorrowRate } from './base/types.js';

// ---------------------------------------------------------------------------

Expand Down Expand Up @@ -7863,7 +7863,7 @@ export default class bitget extends Exchange {
});
}

async fetchIsolatedBorrowRate (symbol: string, params = {}) {
async fetchIsolatedBorrowRate (symbol: string, params = {}): Promise<IsolatedBorrowRate> {
/**
* @method
* @name bitget#fetchIsolatedBorrowRate
Expand Down Expand Up @@ -7927,7 +7927,7 @@ export default class bitget extends Exchange {
return this.parseIsolatedBorrowRate (first, market);
}

parseIsolatedBorrowRate (info, market: Market = undefined) {
parseIsolatedBorrowRate (info, market: Market = undefined): IsolatedBorrowRate {
//
// {
// "symbol": "BTCUSDT",
Expand Down Expand Up @@ -7980,7 +7980,7 @@ export default class bitget extends Exchange {
};
}

async fetchCrossBorrowRate (code: string, params = {}) {
async fetchCrossBorrowRate (code: string, params = {}): Promise<CrossBorrowRate> {
/**
* @method
* @name bitget#fetchCrossBorrowRate
Expand Down

0 comments on commit b0ce488

Please sign in to comment.