Comments (5)
There is no easy way to do this. You must send 3 different requests. I am inserting an example of my own code here for you.Ask what you don't understand. I hope I can help you.
import { Client, ExchangeInfo, RoundStep } from './Binance'
import { FuturesOrderType_LT, Symbol, SymbolLotSizeFilter, OrderSide_LT, SymbolPriceFilter } from 'binance-api-node'
async function GetAvailableBalance() {
return (await Client.futuresAccountInfo()).availableBalance
}
async function CalculatePercentageBalance(percentage: number) {
return (Number(await GetAvailableBalance()) * percentage) / 100
}
async function CalculateQuantity(symbol: string, size: number) {
let FilterSymbolObject: Symbol<FuturesOrderType_LT> = ExchangeInfo.find((Pair) => {
return Pair.symbol === symbol
})!
let StepSizeFilter = FilterSymbolObject.filters.find((Filter) => {
return Filter.filterType === 'MARKET_LOT_SIZE'
}) as SymbolLotSizeFilter
let StepSize = StepSizeFilter ? StepSizeFilter.stepSize : ''
const lastPrice = (await Client.futuresMarkPrice()).find((p) => p.symbol === symbol)!.markPrice
let quantity = size / parseFloat(lastPrice)
quantity = RoundStep(String(quantity), StepSize)
return quantity
}
async function RoundPrice(symbol: string, price: number) {
let FilterSymbolObject: Symbol<FuturesOrderType_LT> = ExchangeInfo.find((Pair) => {
return Pair.symbol === symbol
})!
let TickSizeFilter = FilterSymbolObject.filters.find((Filter) => {
return Filter.filterType === 'PRICE_FILTER'
}) as SymbolPriceFilter
let org_price = RoundStep(String(price), TickSizeFilter.tickSize)
return org_price
}
async function GetPositions(symbol: string) {
let positions = (await Client.futuresAccountInfo()).positions
let position = positions.find((p) => p.symbol === symbol)
if (parseFloat(position?.positionAmt!) === 0) return undefined
return position
}
async function CancelPosition(symbol: string) {
let position = await GetPositions(symbol)
if (!position) return
await Client.futuresOrder({
symbol: symbol,
side: position.positionAmt.startsWith('-') ? 'BUY' : 'SELL',
reduceOnly: 'true',
type: 'MARKET',
positionSide: 'BOTH',
quantity: position.positionAmt.replace('-', '')
})
}
async function CreatePosition(symbol: string, side: OrderSide_LT, quantity: number, tp_percent?: number, sl_percent?: number) {
let pos = await Client.futuresOrder({
symbol: symbol,
side: side, // 'BUY' veya 'SELL'
type: 'MARKET', // Piyasa emri
quantity: String(quantity)
})
let markPrice = (await Client.futuresMarkPrice()).find((p) => p.symbol === symbol)!.markPrice
if (tp_percent && tp_percent !== 0) {
let stopPrice = parseFloat(markPrice)
if (side === 'BUY') stopPrice *= tp_percent / 100 + 1
else stopPrice *= 1 - tp_percent / 100
stopPrice = await RoundPrice(symbol, stopPrice)
await Client.futuresOrder({
symbol: symbol,
type: 'TAKE_PROFIT_MARKET',
quantity: String(quantity),
stopPrice: String(stopPrice),
side: side === 'BUY' ? 'SELL' : 'BUY',
closePosition: 'true',
positionSide: 'BOTH',
timeInForce: 'GTE_GTC'
})
}
if (sl_percent && sl_percent !== 0) {
let stopPrice = parseFloat(markPrice)
if (side === 'BUY') stopPrice *= 1 - sl_percent / 100
else stopPrice *= 1 + sl_percent / 100
stopPrice = await RoundPrice(symbol, stopPrice)
await Client.futuresOrder({
symbol: symbol,
type: 'STOP_MARKET',
quantity: String(quantity),
stopPrice: String(stopPrice),
side: side === 'BUY' ? 'SELL' : 'BUY',
closePosition: 'true',
positionSide: 'BOTH',
timeInForce: 'GTE_GTC'
})
}
return pos
}
export default { GetAvailableBalance, CalculatePercentageBalance, GetPositions, CreatePosition, CancelPosition, CalculateQuantity }
from binance-api-node.
@farukborann thank you for this! Just one more question - assuming the take profit gets hit, does the stop loss order cancel? I wouldn't want the order to just linger around.
from binance-api-node.
@farukborann thanks for sharing the code its awesome. Can you also share a methods ExchangeInfo, RoundStep code ? Thanks
from binance-api-node.
@farukborann thank you for this! Just one more question - assuming the take profit gets hit, does the stop loss order cancel? I wouldn't want the order to just linger around.
They will stop because the orders are related to each other.
It's a bit late, but I wanted to write for information.
from binance-api-node.
RoundStep
Yes, for sure!
export let ExchangeInfo: Symbol<FuturesOrderType_LT>[]
async function GetExchangeInfo() {
try {
const _exchangeInfo = await Client.futuresExchangeInfo()
ExchangeInfo = _exchangeInfo.symbols
Log('Exchange info loaded successfuly.')
} catch (err) {
Log('Error getting exchange info, retrying in 5 seconds.')
setTimeout(GetExchangeInfo, 5000)
}
}
GetExchangeInfo()
// Integers do not require rounding
export function RoundStep(Quantity: string, StepSize: string) {
if (Number.isInteger(Quantity)) return Number(Quantity)
const qtyString = parseFloat(Quantity).toFixed(16)
const desiredDecimals = Math.max(StepSize.indexOf('1') - 1, 0)
const decimalIndex = qtyString.indexOf('.')
return parseFloat(qtyString.slice(0, decimalIndex + desiredDecimals + 1))
}
You must to be run GetExchangeInfo function for one time in my structre but you can change this code for yourself.
Btw i found RoundStep function somewhere on stackoverflow but i dont remember where.
from binance-api-node.
Related Issues (20)
- Partial depth not working
- How do you get the current position info for future account? HOT 1
- Reconnecting-websocket options not working? HOT 1
- TypeError: fetch failed HOT 1
- fix about node:fetch? HOT 1
- Module "crypto" has been externalized for browser compatibility HOT 2
- DeprecationWarning: crypto.DEFAULT_ENCODING is deprecated.
- TypeError: Binance is not a function HOT 2
- futuresCancelBatchOrders lacks return-type annotation HOT 3
- Different data
- quantity parameter on Trailling Stop futuresOrder
- Incorrect data type of batchOrders in futuresBatchOrders
- futuresCancelBatchOrders return type error
- Websocket was closed before the connection was estabilshed with binance-api-node ticker and futuresticker
- Error: Invalid API-key, IP, or permissions for action. HOT 2
- How to keep TCP connection alive for REST requests
- Http-client : _crypto.default.createHmac is not a function
- How to i get a new depositAddress if I need it ?
- How to create valid takeprofit and stoploss in futures?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from binance-api-node.