市价买入委托的特殊情况 - createMarketBuyOrderRequiresPrice
总的说来,当市价委托买入或卖出时,用户只需要指定要买入或卖出的基准货币 的数量。但是然而,有些交易所的市价买入委托单处理采用了不同的方式来计算 委托单价值。
假设你在交易BTC/USD
,目前的BTC市场价格是超过9000 USD。要按市价买入或
卖出,你可以指定数量为 2 BTC,取决于你的委托方向,成交结果将是你的账户
增加或减少18000 USD左右。
但是有些交易所要求按报价货币指定委托单的总价!这背后的逻辑其实很简单, 不是说我要买入或卖出多少基准货币,而是”我想消费多少报价货币“。
在这些交易所进行市价买入委托,你不能将委托单的数量指定为 2 BTC,而是
应当指定委托单的总价,在这个例子中,也就是 18000 USD。采用这种方式处理
市价委托单的交易所,有一个选项createMarketBuyOrderRequiresPrice
,你
可以用它以两种方式指定市价买入委托单的总花费:
第一种是默认的,如果你同时设置了委托数量和价格,那么在ccxt内部将会
简单地按照这个公式(cost = amount * price)
计算出委托单总价格,得到
的总花费就会设置为该市价委托单的报价货币总花费,也就是USD总额。示例
代码如下:
// this example is oversimplified and doesn't show all the code that is
// required to handle the errors and exchange metadata properly
// it shows just the concept of placing a market buy order
const exchange = new ccxt.cex ({
'apiKey': YOUR_API_KEY,
'secret': 'YOUR_SECRET',
'enableRateLimit': true,
// 'options': {
// 'createMarketBuyOrderRequiresPrice': true, // default
// },
})
;(async () => {
// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price
// so that the total cost of the order would be calculated inside the library
// by multiplying the amount over price (amount * price)
const symbol = 'BTC/USD'
const amount = 2 // BTC
const price = 9000 // USD
// cost = amount * price = 2 * 9000 = 18000 (USD)
// note that we don't use createMarketBuyOrder here, instead we use createOrder
// createMarketBuyOrder will omit the price and will not work when
// exchange.options['createMarketBuyOrderRequiresPrice'] = true
const order = await exchange.createOrder (symbol, 'market', 'buy', amount, price)
console.log (order)
})
如果希望自己指定委托单的总花费,那么可以使用第二种方式。这需要先
关闭createMarketBuyOrderRequiresPrice
选项,然后进行设置。示例代码
如下:
const exchange = new ccxt.cex ({
'apiKey': YOUR_API_KEY,
'secret': 'YOUR_SECRET',
'enableRateLimit': true,
'options': {
'createMarketBuyOrderRequiresPrice': false, // switch off
},
})
// or, to switch it off later, after the exchange instantiation, you can do
exchange.options['createMarketBuyOrderRequiresPrice'] = false
;(async () => {
// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price
// so that the total cost of the order would be calculated inside the library
// by multiplying the amount over price (amount * price)
const symbol = 'BTC/USD'
const amount = 2 // BTC
const price = 9000 // USD
cost = amount * price // ← instead of the amount cost goes ↓ here
const order = await exchange.createMarketBuyOrder (symbol, cost)
console.log (order)
})
进一步阅读请参考: