简体   繁体   English

Javascript代码部分未按正确顺序运行

[英]Javascript code portion not running in the right order

Im creating a trading bot on Javascript (I got no prior experience with this language). 我用Javascript创建了一个交易机器人(我以前没有使用这种语言的经验)。 The way the trailing stoploss function runs is: 尾随止损功能的运行方式为:

  • Websocket receives current market price Websocket收到当前市场价格
  • "active" is a boolean variable, if true, run the code “ active”是一个布尔变量,如果为true,则运行代码
  • If price rises a %, cancel old stoploss and add a new one higher. 如果价格上涨%,则取消旧的止损并增加新的止损。

The problem I am getting is the code doesn't run in the right order. 我遇到的问题是代码未按正确的顺序运行。 If you look at the picture, I don't understand why the blue box still executes if active is false. 如果您查看图片,我不明白为什么如果active为false,蓝色框仍然执行。 And because the program runs in the wrong order at times, the websocket stops or acts how it isn't supposed to. 而且由于该程序有时会以错误的顺序运行,因此websocket会停止或采取不应有的行动。

产量

This is my trailing stoploss websocket code: 这是我的追踪止损websocket代码:

function binanceTrailingSLOrder(symbol, orderId, quantity, oldPrice, percentage, active) {

    const clean_trade = client.ws.trades([symbol], trade => { //run websocket
        var livePrice = parseFloat(binance_symbols[symbol]["close"]); //set new price to live price

        if (active == true) {
            binanceCheckOrderStatus(symbol, orderId).then(r => {
                switch (r.status) {
                    case "PENDING":
                        if (livePrice >= (oldPrice * ((100 + percentage) / 100)) && active == true) {
                            active = false;
                            binanceCancelOrder(symbol, orderId).then((r4) => { //Cancel previous SL
                                var newSL = livePrice * ((100 - percentage) / 100);
                                binanceStopOrder(symbol, 'SELL', r4.origQty, newSL, newSL).then((r5) => { //Set new SL
                                    orderId = r5.orderId; quantity = r5.origQty; oldPrice = r5.price;
                                    active = true;
                                }).catch((err) => {
                                    console.log(err);
                                });
                            });
                        }
                        break;
                    default:
                        break;
                }

            });
        }
    });

}

Check order status function: 检查订单状态功能:

//Get specific order status
function binanceCheckOrderStatus(symbol, orderId) {
    if(!orderId){
        console.log("order Id not found");
        return false;
    } else {
        var client = loadBinanceKeys2();

        return client.getOrder({
            symbol: symbol,
            orderId: orderId,
            recvWindow: 1000000
        }).then((order) => {
            return order;
        }).catch((err) => {
            console.log(err);
        });
    }
}

Javascript is asynchronous in nature. Java本质上是异步的。 The function binanceCheckOrderStatus() returns a promise. 函数binanceCheckOrderStatus()返回一个binanceCheckOrderStatus() The execution engine will call this function, and then move on to the next line. 执行引擎将调用此函数,然后继续进行下一行。 The code block after .then(r => only executes after the binanceCheckOrderStatus 's getOrder() is completed. Now in this time period, the active may have become false in other .then() requests. It may be confusing for new developers. Since you are using lot of .then() in your code, you have to understand that the .then() part is only executed after the function before .then() completes the execution. So the function taking less time will execute it's .then() part before the others. So in short, you CANNOT control the order in this scenario unless you know how much time every function will take, which is probably impossible to confirm. For overcoming this problem, you have to use async / await . Or, you need to change your logic so it is less dependent on that deep level promises. binanceCheckOrderStatus .then(r =>之后的代码块仅在binanceCheckOrderStatusgetOrder()完成后才执行。现在在这段时间内,活动对象可能在其他.then()请求中变为false,这可能会使新开发人员感到困惑由于您在代码中使用了大量的.then() ,因此您必须了解.then()部分仅在.then()完成执行之前的函数之后才执行,因此花费较少时间执行的函数.then()部分先于其他部分。因此,简而言之,除非您知道每个函数将花费多少时间,否则您将无法控制顺序,这可能无法确认。要解决此问题,您必须使用async / 等待 ,或者,你需要改变你的逻辑,所以它不太依赖于深层次的承诺。

I am not very sure about what you are trying to achieve here, but here is the idea about how you can solve the ordering problem. 我不太确定您要在这里实现什么,但是这里是有关如何解决订购问题的想法。 It is just a reference code, I have not tested it. 这只是参考代码,我没有测试过。 Just an idea on how you can hold your threads to make sure your code runs in an order using async / await . 只是关于如何保持线程以确保代码使用async / await按顺序运行的想法。

async function binanceTrailingSLOrder(symbol, orderId, quantity, oldPrice, percentage, active) {

    const clean_trade = client.ws.trades([symbol], async trade => { //run websocket
        var livePrice = parseFloat(binance_symbols[symbol]["close"]); //set new price to live price

        if (active == true) {

            try {

            const order = await binanceCheckOrderStatus(symbol, orderId);

            if (!order) {
                throw new Error('order not found')
            }
                switch (order.status) {
                    case "PENDING":
                        if (livePrice >= (oldPrice * ((100 + percentage) / 100)) && active == true) {
                            active = false;

                            const r4 = await binanceCancelOrder(symbol, orderId);
                            if (r4) {
                                var newSL = livePrice * ((100 - percentage) / 100);
                                var r5 = binanceStopOrder(symbol, 'SELL', r4.origQty, newSL, newSL);

                                if (r5) {
                                    orderId = r5.orderId; quantity = r5.origQty; oldPrice = r5.price;
                                    active = true;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            catch(error) {
                console.log('error found: ', error);
            }

        }
    });

}



async function binanceCheckOrderStatus(symbol, orderId) {
    if(!orderId){
        console.log("order Id not found");
        return false;
    } else {
        var client = loadBinanceKeys2();

        return new Promise((resolve, reject) => {
            client.getOrder({
                symbol: symbol,
                orderId: orderId,
                recvWindow: 1000000
            }).then((order) => {
                resolve(order);
            }).catch((err) => {
                reject(err);
            });
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM