Bitburner Stock Market Trading Script Bot – Automatically Buy and Sell Stock for you code

Bitburner Stock Market Trading Script Bot – Automatically Buy and Sell Stock for you code 1 - steamsplay.com
Bitburner Stock Market Trading Script Bot – Automatically Buy and Sell Stock for you code 1 - steamsplay.com

This script will automatically buy and sell stock for you
 
 
You need the WSE account, and 4S upgrades to run this script
 
 
There are 2 variables at line 14/15 which can be changed.
 
The first will amend the confidence you want to buy at (65% default)
 
The second will allow you to set a reserve pool of money
 
 
Due to the nature of stock market, it will sometimes sit without doing much (ie. if it’s not the right time to buy or sell), just leave the game open and it’ll do it’s thing.
 
 

Code

Terminal > nano stockbot.js
 
Copy paste the below code in and save
 
Terminal > run stockbot.js
 
 

// Stock market bot for bitburner, written by steamid/Meng- https://danielyxie.github.io/bitburner/ - [github.io] 
// Runs infinitely - buys and sells stock, hopefully for a profit...
// version 1.21 - Added check for max stocks, cleaned things up a bit, cycle complete prints less frequently

export async function main(ns) {
 ns.print("Starting script here");
 ns.disableLog('sleep');
 ns.disableLog('getServerMoneyAvailable');

 let stockSymbols = ns.stock.getSymbols(); // all symbols
 let portfolio = []; // init portfolio
 let cycle = 0;
// ~~~~~~~You can edit these~~~~~~~~
 const forecastThresh = 0.65; // Buy above this confidence level (forecast%)
 const minimumCash = 50000000; // Minimum cash to keep
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 ns.print("Starting run - Do we own any stocks?"); //Finds and adds any stocks we already own
 for(const stock of stockSymbols){
 let pos = ns.stock.getPosition(stock);
 if(pos[0] > 0){
 portfolio.push({sym: stock, value: pos[1], shares: pos[0]})
 ns.print('Detected: '+ stock + ' quant: '+ pos[0] +' @ '+ pos[1]);
 };
 };

 while(true){
 for(const stock of stockSymbols){ // for each stock symbol
 if (portfolio.findIndex(obj => obj.sym === stock) !== -1){ //if we already have this stock
 let i = portfolio.findIndex(obj => obj.sym === stock); // log index of symbol as i
 if(ns.stock.getAskPrice(stock) >= portfolio.value*1.1){ // if the price is higher than what we bought it at +10% then we SELL
sellStock(stock);
}
else if(ns.stock.getForecast(stock) < 0.4){
sellStock(stock);
}
}

else if (ns.stock.getForecast(stock) >= forecastThresh){ // if the forecast is better than threshold and we don't own then BUY
buyStock(stock);
}
} // end of for loop (iterating stockSymbols)
cycle++;
if (cycle % 5 === 0){ ns.print('Cycle '+ cycle + ' Complete') };
await ns.sleep(6000);
} // end of while true loop

function buyStock(stock) {
let stockPrice = ns.stock.getAskPrice(stock); // Get the stockprice
let shares = stockBuyQuantCalc(stockPrice, stock); // calculate the shares to buy using StockBuyQuantCalc

if (ns.stock.getVolatility(stock) <= 0.05){ // if volatility is < 5%, buy the stock
ns.stock.buy(stock, shares);
ns.print('Bought: '+ stock + ' quant: '+ Math.round(shares) +' @ '+ Math.round(stockPrice));

portfolio.push({sym: stock, value: stockPrice, shares: shares}); //store the purchase info in portfolio
}
}

function sellStock(stock) {
let position = ns.stock.getPosition(stock);
var forecast = ns.stock.getForecast(stock);
if (forecast < 0.55) {
let i = portfolio.findIndex(obj => obj.sym === stock); //Find the stock info in the portfolio
ns.print('SOLD: '+ stock + 'quant: '+ portfolio.shares +'@ '+ portfolio.value);
portfolio.splice(i, 1); // Remove the stock from portfolio
ns.stock.sell(stock, position[0]);

}
};

function stockBuyQuantCalc(stockPrice, stock){ // Calculates how many shares to buy
let playerMoney = ns.getServerMoneyAvailable('home') - minimumCash;
let maxSpend = playerMoney * 0.25;
let calcShares = maxSpend/stockPrice;
let maxShares = ns.stock.getMaxShares(stock);

if (calcShares > maxShares){
return maxShares
}
else {return calcShares}
}
}

 
 

Written by Meng

 
 
Hope you enjoy the post for Bitburner Stock Market Trading Script Bot – Automatically Buy and Sell Stock for you code, If you think we should update the post or something is wrong please let us know via comment and we will fix it how fast as possible! Thank you and have a great day!
 


6 Comments

  1. Same correction needs to occur in the sellStock() function

    ns.print(‘SOLD: ‘+ stock + ‘quant: ‘+ portfolio[i].shares +’@ ‘+ portfolio[i].value);

    I really like the script though and appreciate you sharing it. It gives me an idea of how to use the TIX APIs.

    • Another issue I found is that stockBuyQuantCalc() can return a negative shares number. I had to add a logical && shares > 0 under buyStock(). I also liked the idea of the other commenter where you keep a rolling percentage available. I made minimumCash a global var and added: minimumCash = (ns.getServerMoneyAvailable(“home”) * 0.3) to the stockBuyQuantCalc() for real time updating.

      function buyStock(stock) {
      let stockPrice = ns.stock.getAskPrice(stock); // Get the stockprice
      let shares = stockBuyQuantCalc(stockPrice, stock); // calculate the shares to buy using StockBuyQuantCalc

      if (ns.stock.getVolatility(stock) 0) { // if volatility is < 5%, buy the stock
      ns.stock.buy(stock, shares);
      ns.print('Bought: ' + stock + ' quant: ' + Math.round(shares) + ' @ ' + Math.round(stockPrice));

      portfolio.push({ sym: stock, value: stockPrice, shares: shares }); //store the purchase info in portfolio
      }
      }

  2. Rather than use a static number for the reserve cash, I use a percentage. That way, as you have more assets (including stocks), you’ll have a larger reserve of cash to use. At the same time, when you are BELOW the minimum, it can make small purchases and sales and bring you back up. I do 10% reserve, and that does pretty darn well

  3. Thank you for publishing your script. I used it to become familiar with the ns.stock methods very quickly. I think there is one error in your code in line 31:

    “if(ns.stock.getAskPrice(stock) >= portfolio.value*1.1){
    sellStock(stock);
    }”

    Obviously you want to write “portfolio[i].value”.

    “portfolio.value” returns “null”, since portfolio is an array of objects, not an object itself.

    Greetings!

Leave a Reply

Your email address will not be published.


*