Skip to content

Instantly share code, notes, and snippets.

@pythonlessons
Created December 1, 2020 15:14
Show Gist options
  • Select an option

  • Save pythonlessons/0ba7b644eb4d06a42253d1d192fe0e61 to your computer and use it in GitHub Desktop.

Select an option

Save pythonlessons/0ba7b644eb4d06a42253d1d192fe0e61 to your computer and use it in GitHub Desktop.
BTC_trading_bot_1_step
# Execute one time step within the environment
def step(self, action):
self.crypto_bought = 0
self.crypto_sold = 0
self.current_step += 1
# Set the current price to a random price between open and close
current_price = random.uniform(
self.df.loc[self.current_step, 'Open'],
self.df.loc[self.current_step, 'Close'])
if action == 0: # Hold
pass
elif action == 1 and self.balance > 0:
# Buy with 100% of current balance
self.crypto_bought = self.balance / current_price
self.balance -= self.crypto_bought * current_price
self.crypto_held += self.crypto_bought
elif action == 2 and self.crypto_held>0:
# Sell 100% of current crypto held
self.crypto_sold = self.crypto_held
self.balance += self.crypto_sold * current_price
self.crypto_held -= self.crypto_sold
self.prev_net_worth = self.net_worth
self.net_worth = self.balance + self.crypto_held * current_price
self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held])
# Calculate reward
reward = self.net_worth - self.prev_net_worth
if self.net_worth <= self.initial_balance/2:
done = True
else:
done = False
obs = self._next_observation()
return obs, reward, done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment