Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@bcswaper/apis

Package Overview
Dependencies
Maintainers
0
Versions
126
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bcswaper/apis - npm Package Compare versions

Comparing version 1.0.107 to 1.0.108

2

dist/context.d.ts

@@ -92,2 +92,3 @@ export type IsoString = string;

id: string;
account: string;
subaccountId: string;

@@ -118,2 +119,3 @@ clientId: number;

id: string;
account: string;
subaccountId: string;

@@ -120,0 +122,0 @@ orderId: string;

2

dist/exchange/dydx/accountHandler.js

@@ -1,1 +0,1 @@

export class AccountHandler{constructor(t="ETH-USD",s){this.asset="USDC",this.accountInfo={account:"",subaccount:0,equity:0,balance:0,positions:[],asset:0},this.symbol=t,this.clientCallBackFuncs=s,this.postConstruct()}postConstruct(){this.perpetualPositions=this.defaultPerpetualPositionsProperties(),this.assetPosition=this.defaultAssetPositionProperties(),this.orders=this.defaultOrderProperties(),this.fills=this.defaultFillProperties(),this.transfers=this.defaultTransferProperties()}async initialize(t){console.log("=== initial account data: \n ",JSON.stringify(t));const s=t.contents.subaccount;this.accountInfo.account=s?.address,this.accountInfo.subaccount=s?.subaccountNumber,this.accountInfo.equity=s?.equity,this.accountInfo.balance=s?.freeCollateral,this.perpetualPositions=[];const i=s?.openPerpetualPositions;if(i){const t=i[this.symbol];t&&(this.perpetualPositions.push(t),this.calculatePositions())}const e=t.contents.subaccount?.assetPositions;e&&(this.assetPosition=e[this.asset],this.calculateAsset());const o=t.contents.orders;this.calculateOrders(o)}async update(t){console.log("=== update account data: \n ",JSON.stringify(t));const s=t.contents.perpetualPositions,i=s?.filter((t=>t.market===this.symbol));i?.length>0&&(this.perpetualPositions=i,this.calculatePositions());const e=t.contents.assetPositions,o=e?.filter((t=>t.symbol===this.asset));o?.length>0&&(this.assetPosition=o.at(0),this.calculateAsset());const n=t.contents.orders;this.calculateOrders(n);const c=t.contents.fills;this.calculateFills(c)}calculatePositions(){console.log("=== calculate position ...");const t=[];this.perpetualPositions.forEach((s=>{const i={symbol:this.symbol,side:s.side,size:Number(s.size)};t.push(i)})),this.accountInfo.positions=t,this.clientCallBackFuncs.positionFunc&&this.clientCallBackFuncs.positionFunc(t)}calculateAsset(){console.log("=== calculate asset ..."),this.accountInfo.asset=parseFloat(this.assetPosition?.size||"0"),this.clientCallBackFuncs.accountFunc&&this.clientCallBackFuncs.accountFunc(this.accountInfo)}calculateOrders(t){this.orders=t,this.orders?.forEach((t=>{const s={};Object.assign(s,t),this.clientCallBackFuncs.orderFunc&&this.clientCallBackFuncs.orderFunc(s)}))}calculateFills(t){this.fills=t,this.fills?.forEach((t=>{const s={};Object.assign(s,t),this.clientCallBackFuncs.fillFunc&&this.clientCallBackFuncs.fillFunc(s)}))}getAccountInfo(){return this.accountInfo}defaultPerpetualPositionsProperties(){return[]}defaultAssetPositionProperties(){return{}}defaultOrderProperties(){return[]}defaultFillProperties(){return[]}defaultTransferProperties(){return[]}}export var PerpetualPositionStatus;!function(t){t.OPEN="OPEN",t.CLOSED="CLOSED",t.LIQUIDATED="LIQUIDATED"}(PerpetualPositionStatus||(PerpetualPositionStatus={}));export var APITimeInForce;!function(t){t.GTT="GTT",t.FOK="FOK",t.IOC="IOC"}(APITimeInForce||(APITimeInForce={}));export var APIOrderStatus;!function(t){t.OPEN="OPEN",t.FILLED="FILLED",t.CANCELED="CANCELED",t.BEST_EFFORT_CANCELED="BEST_EFFORT_CANCELED",t.BEST_EFFORT_OPENED="BEST_EFFORT_OPENED",t.UNTRIGGERED="UNTRIGGERED"}(APIOrderStatus||(APIOrderStatus={}));export var Liquidity;!function(t){t.TAKER="TAKER",t.MAKER="MAKER"}(Liquidity||(Liquidity={}));export var FillType;!function(t){t.LIMIT="LIMIT",t.LIQUIDATED="LIQUIDATED",t.LIQUIDATION="LIQUIDATION",t.DELEVERAGED="DELEVERAGED",t.OFFSETTING="OFFSETTING"}(FillType||(FillType={}));export var TransferType;!function(t){t.TRANSFER_IN="TRANSFER_IN",t.TRANSFER_OUT="TRANSFER_OUT",t.DEPOSIT="DEPOSIT",t.WITHDRAWAL="WITHDRAWAL"}(TransferType||(TransferType={}));
export class AccountHandler{constructor(t="ETH-USD",s){this.asset="USDC",this.accountInfo={account:"",subaccount:0,equity:0,balance:0,positions:[],asset:0},this.symbol=t,this.clientCallBackFuncs=s,this.postConstruct()}postConstruct(){this.perpetualPositions=this.defaultPerpetualPositionsProperties(),this.assetPosition=this.defaultAssetPositionProperties(),this.orders=this.defaultOrderProperties(),this.fills=this.defaultFillProperties(),this.transfers=this.defaultTransferProperties()}async initialize(t){console.log("=== initial account data: \n ",JSON.stringify(t));const s=t.contents.subaccount;this.accountInfo.account=s?.address,this.accountInfo.subaccount=s?.subaccountNumber,this.accountInfo.equity=s?.equity,this.accountInfo.balance=s?.freeCollateral,this.perpetualPositions=[];const i=s?.openPerpetualPositions;if(i){const t=i[this.symbol];t&&(this.perpetualPositions.push(t),this.calculatePositions())}const e=t.contents.subaccount?.assetPositions;e&&(this.assetPosition=e[this.asset],this.calculateAsset());const o=t.contents.orders;this.calculateOrders(o)}async update(t){console.log("=== update account data: \n ",JSON.stringify(t));const s=t.contents.perpetualPositions,i=s?.filter((t=>t.market===this.symbol));i?.length>0&&(this.perpetualPositions=i,this.calculatePositions());const e=t.contents.assetPositions,o=e?.filter((t=>t.symbol===this.asset));o?.length>0&&(this.assetPosition=o.at(0),this.calculateAsset());const n=t.contents.orders;this.calculateOrders(n);const c=t.contents.fills;this.calculateFills(c)}calculatePositions(){console.log("=== calculate position ...");const t=[];this.perpetualPositions.forEach((s=>{const i={symbol:this.symbol,side:s.side,size:Number(s.size)};t.push(i)})),this.accountInfo.positions=t,this.clientCallBackFuncs.positionFunc&&this.clientCallBackFuncs.positionFunc(t)}calculateAsset(){console.log("=== calculate asset ..."),this.accountInfo.asset=parseFloat(this.assetPosition?.size||"0"),this.clientCallBackFuncs.accountFunc&&this.clientCallBackFuncs.accountFunc(this.accountInfo)}calculateOrders(t){this.orders=t,this.orders?.forEach((t=>{const s={};Object.assign(s,t),s.account=this.accountInfo.account,this.clientCallBackFuncs.orderFunc&&this.clientCallBackFuncs.orderFunc(s)}))}calculateFills(t){this.fills=t,this.fills?.forEach((t=>{const s={};Object.assign(s,t),s.account=this.accountInfo.account,this.clientCallBackFuncs.fillFunc&&this.clientCallBackFuncs.fillFunc(s)}))}getAccountInfo(){return this.accountInfo}defaultPerpetualPositionsProperties(){return[]}defaultAssetPositionProperties(){return{}}defaultOrderProperties(){return[]}defaultFillProperties(){return[]}defaultTransferProperties(){return[]}}export var PerpetualPositionStatus;!function(t){t.OPEN="OPEN",t.CLOSED="CLOSED",t.LIQUIDATED="LIQUIDATED"}(PerpetualPositionStatus||(PerpetualPositionStatus={}));export var APITimeInForce;!function(t){t.GTT="GTT",t.FOK="FOK",t.IOC="IOC"}(APITimeInForce||(APITimeInForce={}));export var APIOrderStatus;!function(t){t.OPEN="OPEN",t.FILLED="FILLED",t.CANCELED="CANCELED",t.BEST_EFFORT_CANCELED="BEST_EFFORT_CANCELED",t.BEST_EFFORT_OPENED="BEST_EFFORT_OPENED",t.UNTRIGGERED="UNTRIGGERED"}(APIOrderStatus||(APIOrderStatus={}));export var Liquidity;!function(t){t.TAKER="TAKER",t.MAKER="MAKER"}(Liquidity||(Liquidity={}));export var FillType;!function(t){t.LIMIT="LIMIT",t.LIQUIDATED="LIQUIDATED",t.LIQUIDATION="LIQUIDATION",t.DELEVERAGED="DELEVERAGED",t.OFFSETTING="OFFSETTING"}(FillType||(FillType={}));export var TransferType;!function(t){t.TRANSFER_IN="TRANSFER_IN",t.TRANSFER_OUT="TRANSFER_OUT",t.DEPOSIT="DEPOSIT",t.WITHDRAWAL="WITHDRAWAL"}(TransferType||(TransferType={}));

@@ -1,1 +0,1 @@

import{IndexerConfig,ValidatorConfig,Network,IndexerClient,SocketClient,ValidatorClient,CompositeClient,LocalWallet,BECH32_PREFIX,SubaccountInfo,Order_TimeInForce,OrderExecution,OrderSide,OrderTimeInForce,OrderType,MAINNET_CHAIN_ID,ValidatorApiHost,IndexerApiHost,IndexerWSHost}from"@dydxprotocol/v4-client-js";import{IncomingMessageTypes}from"@dydxprotocol/v4-client-js/build/src/clients/socket-client";import{MarketsHandler}from"./marketsHandler";import{AccountHandler}from"./accountHandler";import{OrderbookHandler}from"./orderbookHandler";import{CandlesHandler}from"./candlesHandler";import{TradesHandler}from"./tradesHandler";import{convertResolution}from"./dydxContext";import{CandleResolution}from"../../context";import{AbstractClient,ClientSettings}from"../../client";export class DydxClient extends AbstractClient{constructor(e){super(),this.mainnetIndexerConfig=new IndexerConfig(IndexerApiHost.MAINNET,IndexerWSHost.MAINNET),this.mainnetValidatorConfig=new ValidatorConfig(ValidatorApiHost.MAINNET,MAINNET_CHAIN_ID,{USDC_DENOM:"ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",USDC_DECIMALS:6,USDC_GAS_DENOM:"uusdc",CHAINTOKEN_DENOM:"adydx",CHAINTOKEN_DECIMALS:18}),this.mainnetNetwork=new Network("mainnet",this.mainnetIndexerConfig,this.mainnetValidatorConfig),this.dydxAccInfo=e.account}async initialize(){console.log("initializing ..."),this.accountHandler=new AccountHandler(this.dydxAccInfo.symbol,this.clientCallBackFuncs),this.candlesHandler=new CandlesHandler(this.dydxAccInfo.symbol,this.clientCallBackFuncs),this.marketsHandler=new MarketsHandler(this.dydxAccInfo.symbol),this.orderbookHandler=new OrderbookHandler(this.dydxAccInfo.symbol),this.tradesHandler=new TradesHandler(this.dydxAccInfo.symbol),this.indexerClient=new IndexerClient(this.mainnetNetwork.indexerConfig),this.validatorClient=await ValidatorClient.connect(this.mainnetNetwork.validatorConfig),this.compositeClient=await CompositeClient.connect(this.mainnetNetwork),this.localWallet=await LocalWallet.fromMnemonic(this.dydxAccInfo.mnemonic,BECH32_PREFIX),this.subaccount=new SubaccountInfo(this.localWallet,this.dydxAccInfo.subaccount),this.createSocketClient(),super.initialize(),console.log("done.")}createSocketClient(){this.socketClient=new SocketClient(this.mainnetNetwork.indexerConfig,(()=>{console.log("socket client opened."),console.log("clientCallBackFuncs ...",this.clientCallBackFuncs),console.log("subscribe to dydx account ..."),this.socketClient?.subscribeToSubaccount(this.dydxAccInfo.address,0),this.clientCallBackFuncs.orderBookFunc&&(console.log("subscribe to dydx orderbook ..."),this.socketClient?.subscribeToOrderbook(this.dydxAccInfo.symbol)),this.clientCallBackFuncs.tradesFunc&&(console.log("subscribe to trade ... "),this.socketClient?.subscribeToTrades(this.dydxAccInfo.symbol)),0===this.clientCandleMap?.size&&this.clientCandleMap.set(CandleResolution.DAY1,1),console.log("clientCandleMap ...",this.clientCandleMap),this.clientCandleMap?.forEach(((e,t)=>{console.log("subscribed candle: ",t);const o=convertResolution(t);o?this.socketClient?.subscribeToCandles(this.dydxAccInfo.symbol,o):console.log("error subscribing resolution: ",t)}))}),(()=>{console.log("socket client closed."),this.running&&(console.log("reconnecting ..."),this.socketClient?.connect())}),(e=>{if("string"!=typeof e.data)return void console.error("error data received ",e);const t=e.data;try{const e=JSON.parse(t),o=e.channel;switch(e.type){case IncomingMessageTypes.CONNECTED:console.log("socket client connected.");break;case IncomingMessageTypes.SUBSCRIBED:switch(o){case ChannelTypes.Subaccounts:this.accountHandler.initialize(e);break;case ChannelTypes.Markets:this.marketsHandler.initialize(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.initialize(e);break;case ChannelTypes.Candles:this.candlesHandler.initialize(e);break;case ChannelTypes.Trades:this.tradesHandler.initialize(e);break;default:console.error("unexpected channel: ",o)}break;case IncomingMessageTypes.CHANNEL_DATA:o===ChannelTypes.Subaccounts?this.accountHandler.update(e):console.error("unexpected channel data: ",o);break;case IncomingMessageTypes.CHANNEL_BATCH_DATA:switch(o){case ChannelTypes.Markets:this.marketsHandler.update(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.update(e);break;case ChannelTypes.Candles:this.candlesHandler.update(e);break;case ChannelTypes.Trades:this.tradesHandler.update(e);break;default:console.error("unexpected channel batch data: ",o)}break;default:console.log("received unknown message",e)}}catch(e){console.error("error resolving websocket message:",e)}}),(e=>{console.error("socket client error:",e)})),this.socketClient.connect()}getPrice(){return this.candlesHandler.getPrice()||0}getOrderbook(){return this.orderbookHandler.getOrderbook()}getAccountInfo(){return this.accountHandler.getAccountInfo()}getCandles(e){const t=convertResolution(e);return this.candlesHandler.getCandles(t)}async calculateGoodTilBlock(){return this.validatorClient?this.validatorClient.get.latestBlockHeight().then((e=>e+20)).catch((e=>{throw console.error("error fetching block height:",e),e})):0}async shortTermOrder(e,t,o,n){console.log(`open short term order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}`),this.placeShortTermOrder(e,t,o,n,Order_TimeInForce.TIME_IN_FORCE_UNSPECIFIED,!1)}placeShortTermOrder(e,t,o,n,r,i){this.calculateGoodTilBlock().then((c=>{this.compositeClient?.placeShortTermOrder(this.subaccount,this.dydxAccInfo.symbol,t,o,n,e,c,r,i).catch((e=>console.error("error placing short term short term order:",e)))})).catch((e=>console.error("error calculating good til block on short term order:",e)))}placeMarketOrder(e,t,o,n,r,i){console.log(`market order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}`);const c=OrderType.MARKET,s=OrderExecution.DEFAULT;this.compositeClient?.placeOrder(this.subaccount,this.dydxAccInfo.symbol,c,t,o,n,e,r,600,s,!1,i).catch((e=>console.error("error placing market order:",e)))}async buy(e,t,o){this.placeMarketOrder(e,OrderSide.BUY,t,o,OrderTimeInForce.GTT,!1)}async sell(e,t,o){this.placeMarketOrder(e,OrderSide.SELL,t,o,OrderTimeInForce.GTT,!1)}async close(e,t,o,n){console.log("close order ... "),await this.placeMarketOrder(e,t,o,n,OrderTimeInForce.GTT,!0)}placeLimitOrder(e,t,o,n,r,i=OrderTimeInForce.GTT,c=!1){console.log(`limit order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}, goodTillTime: ${r}`);const s=OrderType.LIMIT,l=OrderExecution.DEFAULT;this.compositeClient?.placeOrder(this.subaccount,this.dydxAccInfo.symbol,s,t,o,n,e,i,r,l,!1,c).catch((e=>console.error("error placing long term post-only order:",e)))}async buyLimit(e,t,o,n=ClientSettings.GoodTillTime){this.placeLimitOrder(e,OrderSide.BUY,t,o,n)}async sellLimit(e,t,o,n=ClientSettings.GoodTillTime){this.placeLimitOrder(e,OrderSide.SELL,t,o,n)}async closeLimit(e,t,o,n,r=ClientSettings.GoodTillTime){console.log("close order limit ... "),await this.placeLimitOrder(e,t,o,n,r,OrderTimeInForce.GTT,!0)}async cancel(e){console.log(`cancel order ****** id : ${e.id}, clientId: ${e.clientId}, type: ${e.type}`);let t=Number(e.orderFlags),o=0,n=0;switch(e.type){case OrderType.LIMIT:switch(e.timeInForce){case OrderTimeInForce.IOC:case OrderTimeInForce.FOK:o=await this.calculateGoodTilBlock();break;default:n=ClientSettings.GoodTillTime}break;case OrderType.MARKET:o=await this.calculateGoodTilBlock()}console.log(`goodTilBlockTime: ${n}, goodTilBlock: ${o}`),this.compositeClient?.cancelOrder(this.subaccount,e.clientId,t,this.dydxAccInfo.symbol,o,n).catch((e=>console.error("error cancelling order:",e)))}destroy(){console.log("dydx client release ..."),delete this.indexerClient,delete this.validatorClient,delete this.compositeClient,delete this.localWallet,this.socketClient?.close(),super.destroy(),console.log("dydx client released.")}}export var ChannelTypes;!function(e){e.Subaccounts="v4_subaccounts",e.Markets="v4_markets",e.Orderbook="v4_orderbook",e.Candles="v4_candles",e.Trades="v4_trades"}(ChannelTypes||(ChannelTypes={}));
import{IndexerConfig,ValidatorConfig,Network,IndexerClient,SocketClient,ValidatorClient,CompositeClient,LocalWallet,BECH32_PREFIX,SubaccountInfo,Order_TimeInForce,OrderExecution,OrderSide,OrderTimeInForce,OrderType,MAINNET_CHAIN_ID,ValidatorApiHost,IndexerApiHost,IndexerWSHost}from"@dydxprotocol/v4-client-js";import{IncomingMessageTypes}from"@dydxprotocol/v4-client-js/build/src/clients/socket-client";import{MarketsHandler}from"./marketsHandler";import{AccountHandler}from"./accountHandler";import{OrderbookHandler}from"./orderbookHandler";import{CandlesHandler}from"./candlesHandler";import{TradesHandler}from"./tradesHandler";import{convertResolution}from"./dydxContext";import{CandleResolution}from"../../context";import{AbstractClient,ClientSettings}from"../../client";export class DydxClient extends AbstractClient{constructor(e){super(),this.mainnetIndexerConfig=new IndexerConfig(IndexerApiHost.MAINNET,IndexerWSHost.MAINNET),this.mainnetValidatorConfig=new ValidatorConfig(ValidatorApiHost.MAINNET,MAINNET_CHAIN_ID,{USDC_DENOM:"ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",USDC_DECIMALS:6,USDC_GAS_DENOM:"uusdc",CHAINTOKEN_DENOM:"adydx",CHAINTOKEN_DECIMALS:18}),this.mainnetNetwork=new Network("mainnet",this.mainnetIndexerConfig,this.mainnetValidatorConfig),this.dydxAccInfo=e.account}async initialize(){console.log("initializing ..."),this.accountHandler=new AccountHandler(this.dydxAccInfo.symbol,this.clientCallBackFuncs),this.candlesHandler=new CandlesHandler(this.dydxAccInfo.symbol,this.clientCallBackFuncs),this.marketsHandler=new MarketsHandler(this.dydxAccInfo.symbol),this.orderbookHandler=new OrderbookHandler(this.dydxAccInfo.symbol),this.tradesHandler=new TradesHandler(this.dydxAccInfo.symbol),this.indexerClient=new IndexerClient(this.mainnetNetwork.indexerConfig),this.validatorClient=await ValidatorClient.connect(this.mainnetNetwork.validatorConfig),this.compositeClient=await CompositeClient.connect(this.mainnetNetwork),this.localWallet=await LocalWallet.fromMnemonic(this.dydxAccInfo.mnemonic,BECH32_PREFIX),this.subaccount=new SubaccountInfo(this.localWallet,this.dydxAccInfo.subaccount),this.createSocketClient(),super.initialize(),console.log("done.")}createSocketClient(){this.socketClient=new SocketClient(this.mainnetNetwork.indexerConfig,(()=>{console.log("socket client opened."),console.log("clientCallBackFuncs ...",this.clientCallBackFuncs),console.log("subscribe to dydx account ..."),this.socketClient?.subscribeToSubaccount(this.dydxAccInfo.address,0),this.clientCallBackFuncs.orderBookFunc&&(console.log("subscribe to dydx orderbook ..."),this.socketClient?.subscribeToOrderbook(this.dydxAccInfo.symbol)),this.clientCallBackFuncs.tradesFunc&&(console.log("subscribe to trade ... "),this.socketClient?.subscribeToTrades(this.dydxAccInfo.symbol)),0===this.clientCandleMap?.size&&this.clientCandleMap.set(CandleResolution.DAY1,1),console.log("clientCandleMap ...",this.clientCandleMap),this.clientCandleMap?.forEach(((e,t)=>{console.log("subscribed candle: ",t);const o=convertResolution(t);o?this.socketClient?.subscribeToCandles(this.dydxAccInfo.symbol,o):console.log("error subscribing resolution: ",t)}))}),(()=>{console.log("socket client closed."),this.running&&(console.log("reconnecting ..."),this.socketClient?.connect())}),(e=>{if("string"!=typeof e.data)return void console.error("error data received ",e);const t=e.data;try{const e=JSON.parse(t),o=e.channel;switch(e.type){case IncomingMessageTypes.CONNECTED:console.log("socket client connected.");break;case IncomingMessageTypes.SUBSCRIBED:switch(o){case ChannelTypes.Subaccounts:this.accountHandler.initialize(e);break;case ChannelTypes.Markets:this.marketsHandler.initialize(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.initialize(e);break;case ChannelTypes.Candles:this.candlesHandler.initialize(e);break;case ChannelTypes.Trades:this.tradesHandler.initialize(e);break;default:console.error("unexpected channel: ",o)}break;case IncomingMessageTypes.CHANNEL_DATA:if(o===ChannelTypes.Subaccounts)this.accountHandler.update(e);else console.error("unexpected channel data: ",o);break;case IncomingMessageTypes.CHANNEL_BATCH_DATA:switch(o){case ChannelTypes.Markets:this.marketsHandler.update(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.update(e);break;case ChannelTypes.Candles:this.candlesHandler.update(e);break;case ChannelTypes.Trades:this.tradesHandler.update(e);break;default:console.error("unexpected channel batch data: ",o)}break;default:console.log("received unknown message",e)}}catch(e){console.error("error resolving websocket message:",e)}}),(e=>{console.error("socket client error:",e)})),this.socketClient.connect()}getPrice(){return this.candlesHandler.getPrice()||0}getOrderbook(){return this.orderbookHandler.getOrderbook()}getAccountInfo(){return this.accountHandler.getAccountInfo()}getCandles(e){const t=convertResolution(e);return this.candlesHandler.getCandles(t)}async calculateGoodTilBlock(){return this.validatorClient?this.validatorClient.get.latestBlockHeight().then((e=>e+20)).catch((e=>{throw console.error("error fetching block height:",e),e})):0}async shortTermOrder(e,t,o,n){console.log(`open short term order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}`),this.placeShortTermOrder(e,t,o,n,Order_TimeInForce.TIME_IN_FORCE_UNSPECIFIED,!1)}placeShortTermOrder(e,t,o,n,r,i){this.calculateGoodTilBlock().then((c=>{this.compositeClient?.placeShortTermOrder(this.subaccount,this.dydxAccInfo.symbol,t,o,n,e,c,r,i).catch((e=>console.error("error placing short term short term order:",e)))})).catch((e=>console.error("error calculating good til block on short term order:",e)))}placeMarketOrder(e,t,o,n,r,i){console.log(`market order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}`);const c=OrderType.MARKET,s=OrderExecution.DEFAULT;this.compositeClient?.placeOrder(this.subaccount,this.dydxAccInfo.symbol,c,t,o,n,e,r,600,s,!1,i).catch((e=>console.error("error placing market order:",e)))}async buy(e,t,o){this.placeMarketOrder(e,OrderSide.BUY,t,o,OrderTimeInForce.GTT,!1)}async sell(e,t,o){this.placeMarketOrder(e,OrderSide.SELL,t,o,OrderTimeInForce.GTT,!1)}async close(e,t,o,n){console.log("close order ... "),await this.placeMarketOrder(e,t,o,n,OrderTimeInForce.GTT,!0)}placeLimitOrder(e,t,o,n,r,i=OrderTimeInForce.GTT,c=!1){console.log(`limit order ****** clientId: ${e}, side : ${t}, price: ${o}, size: ${n}, goodTillTime: ${r}`);const s=OrderType.LIMIT,l=OrderExecution.DEFAULT;this.compositeClient?.placeOrder(this.subaccount,this.dydxAccInfo.symbol,s,t,o,n,e,i,r,l,!1,c).catch((e=>console.error("error placing long term post-only order:",e)))}async buyLimit(e,t,o,n=ClientSettings.GoodTillTime){this.placeLimitOrder(e,OrderSide.BUY,t,o,n)}async sellLimit(e,t,o,n=ClientSettings.GoodTillTime){this.placeLimitOrder(e,OrderSide.SELL,t,o,n)}async closeLimit(e,t,o,n,r=ClientSettings.GoodTillTime){console.log("close order limit ... "),await this.placeLimitOrder(e,t,o,n,r,OrderTimeInForce.GTT,!0)}async cancel(e){console.log(`cancel order ****** id : ${e.id}, clientId: ${e.clientId}, type: ${e.type}`);let t=Number(e.orderFlags),o=0,n=0;switch(e.type){case OrderType.LIMIT:switch(e.timeInForce){case OrderTimeInForce.IOC:case OrderTimeInForce.FOK:o=await this.calculateGoodTilBlock();break;default:n=ClientSettings.GoodTillTime}break;case OrderType.MARKET:o=await this.calculateGoodTilBlock()}console.log(`goodTilBlockTime: ${n}, goodTilBlock: ${o}`),this.compositeClient?.cancelOrder(this.subaccount,e.clientId,t,this.dydxAccInfo.symbol,o,n).catch((e=>console.error("error cancelling order:",e)))}destroy(){console.log("dydx client release ..."),delete this.indexerClient,delete this.validatorClient,delete this.compositeClient,delete this.localWallet,this.socketClient?.close(),super.destroy(),console.log("dydx client released.")}}export var ChannelTypes;!function(e){e.Subaccounts="v4_subaccounts",e.Markets="v4_markets",e.Orderbook="v4_orderbook",e.Candles="v4_candles",e.Trades="v4_trades"}(ChannelTypes||(ChannelTypes={}));

@@ -1,1 +0,1 @@

import{conerr}from"../../client";import{PositionSide}from"../../context";import{convertOrderSide,convertOrderStatus,convertOrderType}from"./okxContext";export class AccountHandler{constructor(t="ETH-USD",e){this.accountInfo={account:"",subaccount:0,equity:0,balance:0,positions:[],asset:0},this.symbol=t,this.clientCallBackFuncs=e}async resolveAccount(t,e){console.log("=== resolve account data: \n ",JSON.stringify(e)),this.accountInfo.account=t,this.accountInfo.equity=e.totalEq,this.accountInfo.balance=e.adjEq,this.accountInfo.asset=e.isoEq,this.clientCallBackFuncs.accountFunc&&this.clientCallBackFuncs.accountFunc(this.accountInfo)}async resolvePostitions(t,e){if(console.log("=== resolve positions data: \n ",JSON.stringify(e)),e.instId!==this.symbol)return void conerr("some thing wrong with the symbol: ",e.instId);const o=[],n={symbol:this.symbol,side:this.getPositionSide(e.posSide),size:Number(e.pos)};o.push(n),this.accountInfo.positions=o,this.clientCallBackFuncs.positionFunc&&this.clientCallBackFuncs.positionFunc(o)}async resolveOrder(t,e){console.log("=== resolve order data: \n ",JSON.stringify(e));const o={id:e.ordId,subaccountId:"",clientId:Number(e.clOrdId),side:convertOrderSide(e.side),size:Number(e.sz),ticker:e.instId,price:Number(e.px),type:convertOrderType(e.ordType),reduceOnly:Boolean(e.reduceOnly),status:convertOrderStatus(e.state),orderFlags:e.tag,totalFilled:Number(e.accFillSz),fee:Number(e.fee),filledPrice:Number(e.fillPx),clientMetadata:e.tag,updatedAt:e.uTime};this.clientCallBackFuncs.orderFunc&&this.clientCallBackFuncs.orderFunc(o)}async resolveFill(t,e){console.log("=== resolve fill data: \n ",JSON.stringify(e));const o={id:e.tradeId,orderId:e.ordId,side:convertOrderSide(e.side),size:Number(e.fillSz),ticker:e.instId,price:Number(e.fillPx)};this.clientCallBackFuncs.fillFunc&&this.clientCallBackFuncs.fillFunc(o)}getAccountInfo(){return this.accountInfo}getPositionSide(t){return"long"===t?PositionSide.LONG:"short"===t?PositionSide.SHORT:null}}
import{conerr}from"../../client";import{PositionSide}from"../../context";import{convertOrderSide,convertOrderStatus,convertOrderType}from"./okxContext";export class AccountHandler{constructor(t="ETH-USD",e){this.accountInfo={account:"",subaccount:0,equity:0,balance:0,positions:[],asset:0},this.symbol=t,this.clientCallBackFuncs=e}async resolveAccount(t,e){console.log("=== resolve account data: \n ",JSON.stringify(e)),this.accountInfo.account=t,this.accountInfo.equity=e.totalEq,this.accountInfo.balance=e.adjEq,this.accountInfo.asset=e.isoEq,this.clientCallBackFuncs.accountFunc&&this.clientCallBackFuncs.accountFunc(this.accountInfo)}async resolvePostitions(t,e){if(console.log("=== resolve positions data: \n ",JSON.stringify(e)),e.instId!==this.symbol)return void conerr("some thing wrong with the symbol: ",e.instId);const o=[],n={symbol:this.symbol,side:this.getPositionSide(e.posSide),size:Number(e.pos)};o.push(n),this.accountInfo.positions=o,this.clientCallBackFuncs.positionFunc&&this.clientCallBackFuncs.positionFunc(o)}async resolveOrder(t,e){console.log("=== resolve order data: \n ",JSON.stringify(e));const o={id:e.ordId,account:t,subaccountId:"",clientId:Number(e.clOrdId),side:convertOrderSide(e.side),size:Number(e.sz),ticker:e.instId,price:Number(e.px),type:convertOrderType(e.ordType),reduceOnly:Boolean(e.reduceOnly),status:convertOrderStatus(e.state),orderFlags:e.tag,totalFilled:Number(e.accFillSz),fee:Number(e.fee),filledPrice:Number(e.fillPx),clientMetadata:e.tag,updatedAt:e.uTime};this.clientCallBackFuncs.orderFunc&&this.clientCallBackFuncs.orderFunc(o)}async resolveFill(t,e){console.log("=== resolve fill data: \n ",JSON.stringify(e));const o={id:e.tradeId,account:t,orderId:e.ordId,side:convertOrderSide(e.side),size:Number(e.fillSz),ticker:e.instId,price:Number(e.fillPx)};this.clientCallBackFuncs.fillFunc&&this.clientCallBackFuncs.fillFunc(o)}getAccountInfo(){return this.accountInfo}getPositionSide(t){return"long"===t?PositionSide.LONG:"short"===t?PositionSide.SHORT:null}}

@@ -1,1 +0,1 @@

import hmacSHA256 from"crypto-js/hmac-sha256";import Base64 from"crypto-js/enc-base64";import{AccountHandler}from"./accountHandler";import{OrderbookHandler}from"./orderbookHandler";import{CandlesHandler}from"./candlesHandler";import{OrderSide,OrderType}from"../../context";import{AbstractClient,conerr,conlog}from"../../client";import{convertResolution,OkxConstants}from"./okxContext";import{OkxSocketClient}from"./okxWebSocket";import{TickerHandler}from"./tickerHandler";import{OkxHttpClient}from"./okHttpClient";export class OkxClient extends AbstractClient{constructor(e){super(),this.publicEndpoint=OkxConstants.DEMO_PUBLIC_ENDPOINT,this.privateEndpoint=OkxConstants.DEMO_PRIVATE_ENDPOINT,this.okxAccInfo=e.account,this.okxAccInfo.formally&&(this.publicEndpoint=OkxConstants.PUBLIC_ENDPOINT,this.privateEndpoint=OkxConstants.PRIVATE_ENDPOINT)}async initialize(){conlog("initializing ..."),this.accountHandler=new AccountHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.tickerHandler=new TickerHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.candlesHandler=new CandlesHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.orderbookHandler=new OrderbookHandler(this.okxAccInfo.symbol),this.okxHttpClient=new OkxHttpClient(this.okxAccInfo),this.clientCandleMap?.forEach((async(e,t)=>{conlog("initial candle: ",t);const n=convertResolution(t);n?await this.okxHttpClient.getCandles(this.okxAccInfo.symbol,n):conlog("error initial resolution: ",t)})),this.createSocketClient(),super.initialize(),conlog("done.")}createSocketClient(){this.privateWss=new OkxSocketClient(this.privateEndpoint,(()=>{if(conlog(`socket ${this.privateWss} opened.`),this.clientCallBackFuncs.tickFunc){conlog("subscribed ticker ...");const e={channel:"tickers",instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[e]})}this.clientCallBackFuncs.candleFunc&&(conlog("clientCandleMap ...",this.clientCandleMap),this.clientCandleMap?.forEach(((e,t)=>{conlog("subscribed candle: ",t);const n=convertResolution(t);if(!n)return void conlog("error subscribing resolution: ",t);const o={channel:n,instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[o]})}))),conlog("login ..."),this.login()}),(e=>{if(conlog("message received ...",e),"string"!=typeof e.data)return void conerr("error message received: ",e);const t=e.data;if("pong"!==t)try{const e=JSON.parse(t),n=e?.event,o=e?.code;let s=!1;if("string"==typeof o?s="0"!==o:n===EventType.Error&&(s=!0),s)return void conerr("error: ",t);if(n){if(conlog("event: ",t),n===EventType.Login){conlog("clientCallBackFuncs ...",this.clientCallBackFuncs),conlog("subscribe to okx account/positions ...");const e={channel:"account",ccy:this.okxAccInfo.symbol},t={channel:"positions",instType:"SWAP",instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[e,t]}),this.clientCallBackFuncs.orderBookFunc&&conlog("orderbook not supported yet ..."),this.clientCallBackFuncs.tradesFunc&&conlog("trade not supported yet ... ")}return}const r=e.arg.channel,c=e.arg.uid,i=e.data[0];switch(r){case ChannelType.Account:this.accountHandler.resolveAccount(c,i);break;case ChannelType.Candle:this.candlesHandler.resolve(r,i);break;case ChannelType.Fills:this.accountHandler.resolveFill(c,i);break;case ChannelType.Orders:this.accountHandler.resolveOrder(c,i);break;case ChannelType.Positions:this.accountHandler.resolvePostitions(c,i);break;case ChannelType.Tickers:this.tickerHandler.resolve(i);break;default:conlog("received unknown message",i)}}catch(e){conerr("error resolving websocket message:",e)}}),(()=>{conlog(`socket ${this.privateWss} closed.`),this.running&&(conlog("reconnecting ..."),this.privateWss?.connect())}),(e=>{conerr(`socket ${this.privateWss} error:`,e)})),this.privateWss.connect()}async login(){const e=(""+Date.now()).slice(0,-3),t=`${e}GET/users/self/verify`,n=Base64.stringify(hmacSHA256(t,this.okxAccInfo.secretKey??"")),o={op:"login",args:[{apiKey:this.okxAccInfo.apiKey??"",passphrase:this.okxAccInfo.passphrase??"",timestamp:e,sign:n}]};this.privateWss.send(o)}getPrice(){return this.tickerHandler.getPrice()||0}getOrderbook(){return this.orderbookHandler.getOrderbook()}getAccountInfo(){return this.accountHandler.getAccountInfo()}getCandles(e){const t=convertResolution(e);return this.candlesHandler.getCandles(t)}async placeOrder(e,t,n,o,s,r,c="isolated"){conlog(`place order ****** clientId: ${e}, side : ${t}, orderType:${n}, price: ${o}, size: ${s}`);const i={clOrdId:e.toString(),side:t.toLowerCase(),instId:this.okxAccInfo.symbol,tdMode:c,ordType:n.toLowerCase(),px:o,sz:s,reduceOnly:r},a={id:e,op:"order",args:[i]};this.privateWss.send(a)}async placeMarketOrder(e,t,n,o){this.placeOrder(e,t,OrderType.MARKET,0,n,o)}async buy(e,t){this.placeMarketOrder(e,OrderSide.BUY,t,!1)}async sell(e,t){this.placeMarketOrder(e,OrderSide.SELL,t,!1)}async close(e,t,n){conlog("close order ... "),await this.placeMarketOrder(e,t,n,!0)}async placeLimitOrder(e,t,n,o,s){this.placeOrder(e,t,OrderType.MARKET,0,o,s)}async buyLimit(e,t,n){this.placeLimitOrder(e,OrderSide.BUY,t,n,!1)}async sellLimit(e,t,n){this.placeLimitOrder(e,OrderSide.SELL,t,n,!1)}async closeLimit(e,t,n,o){conlog("close order limit ... "),await this.placeLimitOrder(e,t,n,o,!0)}async cancel(e){conlog(`cancel order ****** id : ${e.id}, clientId: ${e.clientId}, type: ${e.type}`);const t={instId:e.ticker,ordId:e.id},n={id:Date.now().toString(),op:"cancel-order",args:[t]};this.privateWss.send(n)}destroy(){conlog("okx client release ..."),this.privateWss?.close(),super.destroy(),conlog("okx client released.")}}
import hmacSHA256 from"crypto-js/hmac-sha256";import Base64 from"crypto-js/enc-base64";import{AccountHandler}from"./accountHandler";import{OrderbookHandler}from"./orderbookHandler";import{CandlesHandler}from"./candlesHandler";import{OrderSide,OrderType}from"../../context";import{AbstractClient,conerr,conlog}from"../../client";import{convertResolution,OkxConstants}from"./okxContext";import{OkxSocketClient}from"./okxWebSocket";import{TickerHandler}from"./tickerHandler";import{OkxHttpClient}from"./okHttpClient";export class OkxClient extends AbstractClient{constructor(e){super(),this.publicEndpoint=OkxConstants.DEMO_PUBLIC_ENDPOINT,this.privateEndpoint=OkxConstants.DEMO_PRIVATE_ENDPOINT,this.okxAccInfo=e.account,this.okxAccInfo.formally&&(this.publicEndpoint=OkxConstants.PUBLIC_ENDPOINT,this.privateEndpoint=OkxConstants.PRIVATE_ENDPOINT)}async initialize(){conlog("initializing ..."),this.accountHandler=new AccountHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.tickerHandler=new TickerHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.candlesHandler=new CandlesHandler(this.okxAccInfo.symbol,this.clientCallBackFuncs),this.orderbookHandler=new OrderbookHandler(this.okxAccInfo.symbol),this.okxHttpClient=new OkxHttpClient(this.okxAccInfo),this.clientCandleMap?.forEach((async(e,t)=>{conlog("initial candle: ",t);const n=convertResolution(t);if(!n)return void conlog("error initial resolution: ",t);await this.okxHttpClient.getCandles(this.okxAccInfo.symbol,n)})),this.createSocketClient(),super.initialize(),conlog("done.")}createSocketClient(){this.privateWss=new OkxSocketClient(this.privateEndpoint,(()=>{if(conlog(`socket ${this.privateWss} opened.`),this.clientCallBackFuncs.tickFunc){conlog("subscribed ticker ...");const e={channel:"tickers",instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[e]})}this.clientCallBackFuncs.candleFunc&&(conlog("clientCandleMap ...",this.clientCandleMap),this.clientCandleMap?.forEach(((e,t)=>{conlog("subscribed candle: ",t);const n=convertResolution(t);if(!n)return void conlog("error subscribing resolution: ",t);const o={channel:n,instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[o]})}))),conlog("login ..."),this.login()}),(e=>{if(conlog("message received ...",e),"string"!=typeof e.data)return void conerr("error message received: ",e);const t=e.data;if("pong"!==t)try{const e=JSON.parse(t),n=e?.event,o=e?.code;let s=!1;if("string"==typeof o?s="0"!==o:n===EventType.Error&&(s=!0),s)return void conerr("error: ",t);if(n){if(conlog("event: ",t),n===EventType.Login){conlog("clientCallBackFuncs ...",this.clientCallBackFuncs),conlog("subscribe to okx account/positions ...");const e={channel:"account",ccy:this.okxAccInfo.symbol},t={channel:"positions",instType:"SWAP",instId:this.okxAccInfo.symbol};this.privateWss.send({op:"subscribe",args:[e,t]}),this.clientCallBackFuncs.orderBookFunc&&conlog("orderbook not supported yet ..."),this.clientCallBackFuncs.tradesFunc&&conlog("trade not supported yet ... ")}return}const r=e.arg.channel,c=e.arg.uid,i=e.data[0];switch(r){case ChannelType.Account:this.accountHandler.resolveAccount(c,i);break;case ChannelType.Candle:this.candlesHandler.resolve(r,i);break;case ChannelType.Fills:this.accountHandler.resolveFill(c,i);break;case ChannelType.Orders:this.accountHandler.resolveOrder(c,i);break;case ChannelType.Positions:this.accountHandler.resolvePostitions(c,i);break;case ChannelType.Tickers:this.tickerHandler.resolve(i);break;default:conlog("received unknown message",i)}}catch(e){conerr("error resolving websocket message:",e)}}),(()=>{conlog(`socket ${this.privateWss} closed.`),this.running&&(conlog("reconnecting ..."),this.privateWss?.connect())}),(e=>{conerr(`socket ${this.privateWss} error:`,e)})),this.privateWss.connect()}async login(){const e=(""+Date.now()).slice(0,-3),t=`${e}GET/users/self/verify`,n=Base64.stringify(hmacSHA256(t,this.okxAccInfo.secretKey??"")),o={op:"login",args:[{apiKey:this.okxAccInfo.apiKey??"",passphrase:this.okxAccInfo.passphrase??"",timestamp:e,sign:n}]};this.privateWss.send(o)}getPrice(){return this.tickerHandler.getPrice()||0}getOrderbook(){return this.orderbookHandler.getOrderbook()}getAccountInfo(){return this.accountHandler.getAccountInfo()}getCandles(e){const t=convertResolution(e);return this.candlesHandler.getCandles(t)}async placeOrder(e,t,n,o,s,r,c="isolated"){conlog(`place order ****** clientId: ${e}, side : ${t}, orderType:${n}, price: ${o}, size: ${s}`);const i={clOrdId:e.toString(),side:t.toLowerCase(),instId:this.okxAccInfo.symbol,tdMode:c,ordType:n.toLowerCase(),px:o,sz:s,reduceOnly:r},a={id:e,op:"order",args:[i]};this.privateWss.send(a)}async placeMarketOrder(e,t,n,o){this.placeOrder(e,t,OrderType.MARKET,0,n,o)}async buy(e,t){this.placeMarketOrder(e,OrderSide.BUY,t,!1)}async sell(e,t){this.placeMarketOrder(e,OrderSide.SELL,t,!1)}async close(e,t,n){conlog("close order ... "),await this.placeMarketOrder(e,t,n,!0)}async placeLimitOrder(e,t,n,o,s){this.placeOrder(e,t,OrderType.MARKET,0,o,s)}async buyLimit(e,t,n){this.placeLimitOrder(e,OrderSide.BUY,t,n,!1)}async sellLimit(e,t,n){this.placeLimitOrder(e,OrderSide.SELL,t,n,!1)}async closeLimit(e,t,n,o){conlog("close order limit ... "),await this.placeLimitOrder(e,t,n,o,!0)}async cancel(e){conlog(`cancel order ****** id : ${e.id}, clientId: ${e.clientId}, type: ${e.type}`);const t={instId:e.ticker,ordId:e.id},n={id:Date.now().toString(),op:"cancel-order",args:[t]};this.privateWss.send(n)}destroy(){conlog("okx client release ..."),this.privateWss?.close(),super.destroy(),conlog("okx client released.")}}
{
"name": "@bcswaper/apis",
"version": "1.0.107",
"version": "1.0.108",
"main": "dist/index.js",

@@ -5,0 +5,0 @@ "author": "flare.doo@gmail.com",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc