View file src/colab/binance_grid_trading.py - Download

# -*- coding: utf-8 -*-
"""binance_grid_trading.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1MUzGQR534yMDNI0SauNqK-Quoy930ldi

SIMULATION OF BINANCE GRID TRADING

Get the prices here : https://www.binance.com/en/landing/data
and upload them to your Google Drive.
"""

from google.colab import drive
drive.mount('/content/drive')

import numpy as np
from datetime import datetime, timedelta

def load_hist(filename):
  n = 0
  global price_hist

  f = open(filename)
  while (line := f.readline()) != '':
    fields = line.strip().split(',')
    dt = datetime.utcfromtimestamp(int(fields[0])/1000)
    high = float(fields[2])
    low = float(fields[3])
    if float(fields[1]) <= float(fields[4]): # up candle
      first = low
      second = high
    else: # down candle
      first = high
      second = low
    price_hist[dt] = first
    price_hist[dt + timedelta(milliseconds=500)] = second
    n = n+1

  f.close()
  print(f"{n} candles loaded")

price_hist = {}

load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-02.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-03.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-04.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-05.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-06.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-07.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-08.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-09.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-10.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-11.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-12.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-13.csv')
load_hist('drive/MyDrive/BTCUSDT-1s-2024-09-14.csv')

import matplotlib.pyplot as plt

plt.figure(figsize=(15,6))
plt.plot(list(price_hist.keys()), list(price_hist.values()))
plt.show()

def compute_params():

  global price_step
  global order_amount
  global fees

  price_step = (high - low) / steps
  order_amount = (usdt_amount - reserved) / ((steps * 1.054) + 1.05)
  fees = order_amount / 1000

# Parameters
low         = 55738.82  # @param {type:"number"}
high        = 60671.96  # @param {type:"number"}
steps       = 19        # @param {type:"number"}
usdt_amount = 15000     # @param {type:"number"}
stop_loss   = 1         # @param {type:"number"}
take_profit = 64000     # @param {type:"number"}
reserved    = 42.86     # @param {type:"number"}

# Calculated values
compute_params()

print(f"Price Step: {price_step:7.2f}")
print(f"Order Amount: {order_amount:7.2f}")
print(f"Fees: {fees:7.4f}")

import math

def level_of_price(price):
  if price < low: return -1
  if price > high: return steps
  l = math.floor((price - low) / price_step)
  return l

level_of_price(61000)

def price_of_level(level):
  price = low + level * price_step
  return price

price_of_level(3)

init_price = list(price_hist.values())[0]
print(init_price)

# Commented out IPython magic to ensure Python compatibility.
# %%script echo Disabled
# 
# # Répartir usdt_amount proportionnellement au nombre de lignes en dessous du cours initial pour usdt et au dessus du cours initial pour crypto
# usdt = usdt_amount * 6 / 20
# crypto = (usdt_amount * 14 / 20) / init_price
# print(f"Start with {usdt} USDT and {crypto} BTC")

for i in range(steps+1):
  print(f"{i:3} {price_of_level(i):9.2f}")

print(list(price_hist.keys())[0])

print(list(price_hist.keys())[-1])

dt1 = list(price_hist.keys())[1000]
print(dt1)

dt_begin = list(price_hist.keys())[0]
dt_end = list(price_hist.keys())[-1]
duration = dt_end - dt_begin
print(duration)
if duration.total_seconds() / 3600 <= 48:
  first_hour = dt_begin.replace(minute=0, second=0, hour=dt_begin.hour+1)
else:
  first_hour = dt_begin.replace(hour=0, minute=0, second=0, day=dt_begin.day+1)
print(first_hour)
print(first_hour + timedelta(hours=1))

def draw_chart():
  plt.figure(figsize=(15,6))
  plt.plot(list(price_hist.keys()), list(price_hist.values()))
  hour = first_hour
  while hour < dt_end:
    plt.axvline(x=hour, color='grey', linestyle='-')
    if duration.total_seconds() / 3600 <= 48:
      hour = hour + timedelta(hours=1)
    else:
      hour = hour + timedelta(days=1)
  for i in range(steps+1):
    plt.axhline(y=price_of_level(i), color='grey', linestyle='-')
  plt.show()

draw_chart()

crypto_hist = {}

def trade(price_hist, disp=False):

  #global usdt
  #global crypto

  global crypto_hist

  # Répartir usdt_amount proportionnellement au nombre de lignes en dessous du cours initial pour usdt et au dessus du cours initial pour crypto
  init_price = list(price_hist.values())[0]
  usdt = usdt_amount * (init_price - low) / (high - low)
  crypto = (usdt_amount - usdt) / init_price
  crypto_hist = {}

  if disp:
    print(f"Initial price: {init_price:9.2f}, USDT: {usdt:9.2f}, crypto: {crypto:9.6f}")

  level = level_of_price(init_price)
  trend = 0
  nt = 0

  for dt, price in price_hist.items():

    if price < stop_loss: break

    if price > take_profit: break

    previous_level = level
    level = level_of_price(price)


    if level < previous_level:
      for i in range(previous_level, level, -1):
        previous_trend = trend
        trend = -1
        if trend == previous_trend:
          nt = nt + 1
          trade_price = price_of_level(i)
          # Buy cryptos for order_amount USDT
          usdt = usdt - order_amount - fees
          crypto_hist[dt - timedelta(milliseconds=100)] = crypto
          crypto = crypto + order_amount / trade_price
          crypto_hist[dt] = crypto
          total = usdt + crypto * price
          if disp:
            print(f"{dt.strftime('%Y-%m-%d %H:%M:%S')} L{i:3d} ({trade_price:9.2f} ) baisse: {nt:3d} ACHAT -> USDT:{usdt:9.2f}, crypto:{crypto:9.6f}, total:{total:9.2f} gain:{total-usdt_amount:9.2f}")

    elif level > previous_level:
      for i in range(previous_level, level):
        previous_trend = trend
        trend = 1
        if trend == previous_trend:
          nt = nt + 1
          trade_price = price_of_level(i+1)
          # Sell cryptos for order_amount USDT
          usdt = usdt + order_amount - fees
          crypto_hist[dt - timedelta(milliseconds=100)] = crypto
          crypto = crypto - order_amount / trade_price
          crypto_hist[dt] = crypto
          total = usdt + crypto * price
          if disp:
            print(f"{dt.strftime('%Y-%m-%d %H:%M:%S')} L{i:3d} ({trade_price:9.2f} ) hausse: {nt:3d} VENTE -> USDT:{usdt:9.2f}, crypto:{crypto:9.6f}, total:{total:9.2f} gain:{total-usdt_amount:9.2f}")

  return total - usdt_amount

def draw_crypto_hist():
  plt.figure(figsize=(15,6))
  x_values = list(crypto_hist.keys())
  y_values = list(crypto_hist.values())
  plt.plot(x_values, y_values)
  plt.show()

steps = 19
compute_params()
trade(price_hist, True)

draw_crypto_hist()

steps = 18
compute_params()
trade(price_hist, False)

gains = [0 for i in range(0, 30)]

for steps in range(2, 30):
  compute_params()
  gain = trade(price_hist, False)
  gains[steps] = gain
  print(f"{steps:3d} steps: price step:{price_step:8.2f} gain:{gain:8.2f}")

plt.figure(figsize=(15,6))
plt.plot(gains)
plt.show()

steps = 5
compute_params()
draw_chart()
trade(price_hist, True)

draw_crypto_hist()