Home > Blockchain >  Change Variable inside loop in R
Change Variable inside loop in R

Time:04-18

This code generates a signal and makes an order request to an exchange. After the order request has been made, the in_position variable that is marked as false should turn true and no more order requests should be made. However, order requests are still being made. Can someone please suggest a solution. The get_buy_or_sell_signals function is placed within a while loop.

Blockquote }

in_position = FALSE  

get_buy_or_sell_signals <- function(data){

  in_position
  print("looking for signals")
  print(tail(data))

  if(data$class[nrow(data)] == "UP" & data$trend[nrow(data)] == TRUE){
    print("will make an order if not in position")
    if(in_position == FALSE){
       send_signal_buy <- BOTS_signal(symbol = "ETHUSDT",side = 
       "buy",bot_name = bot_name, bot_key = bot_key,limitPrice = 
       as.character(data$close[nrow(data)]*1.12))
       in_position = TRUE
       print(in_position)
    }  else{
       print("Already in position")
    }  
  }

  if(data$class[nrow(data)] == "DOWN" && data$trend[nrow(data)] == FALSE){
    print("time to close")
    if(in_position == TRUE){
      send_signal_sell <- BOTS_signal(symbol = "ETHUSDT",side = 
      "buy",bot_name = bot_name, bot_key = bot_key,limitPrice = 
       as.character(data$close[nrow(data)]*0.86))
      in_position = FALSE
  
    } else{
      print("not in position, nothing to do")
    }

  }
}

CodePudding user response:

Your problem is that in_position is in the scope of the function, not global scope, so will not update the variable of the same name outside of the function.

Look at this minimal example:

in_position <- FALSE

change_position1 <- function() {
    in_position<- TRUE
}

change_position1()

print(in_position) # FALSE

One, generally inadvisable way (particularly in a for loop), to update a variable in the parent scope is to use the <<- operator as follows:

in_position <- FALSE
change_position2 <- function() {
    in_position <<- TRUE
}

change_position2()
print(in_position) # TRUE

The better way is to use a function return value:

# Set to FALSE again
in_position <- FALSE

change_position3 <- function() {
    in_position <- TRUE
    return(in_position)
}

in_position <- change_position3()

print(in_position) # TRUE

Have a read about scope in R to understand the details.

  •  Tags:  
  • r
  • Related