View file src/colab/yfinance_grid_trading.py - Download

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

Automatically generated by Colab.

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

Grid trading with yfinance prices
"""

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

# %%script echo Disabled
# Uncomment previous line if this cell has already been run

import yfinance as yf
from datetime import datetime

start = '2024-09-10'
end = '2024-09-15'

btc_usd = yf.Ticker('BTC-USD')
data = btc_usd.history(interval='1m',
 start=start,
 end=end)
print(data.head)

f = open('drive/MyDrive/btc_usd.txt', 'w')

for i in range(len(data)):
  f.write(f"{data.index[i]};{data.iloc[i,0]}\n")

f.close()

import numpy as np

n = 0
price_hist = {}

f = open('drive/MyDrive/btc_usd.txt')
while (line := f.readline()) != '':
  fields = line.strip().split(';')
  jour = fields[0][0:10]
  if jour >= start and jour < end:
    dt = np.datetime64(fields[0][0:19])
    price_hist[dt] = float(fields[1])
  n = n+1
print(n)
f.close()

import matplotlib.pyplot as plt

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

# 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

price_step = (high - low) / steps
print(f"Price Step: {price_step:7.2f}")

order_amount = (usdt_amount - reserved) / ((steps * 1.054) + 1.05)
print(f"Order Amount: {order_amount:7.2f}")

fees = order_amount / 1000
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]

usdt = usdt_amount * 3 / 19
crypto = (usdt_amount * 16 / 19) / init_price
print(f"Start with {usdt} USDT and {crypto} BTC")

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

plt.figure(figsize=(15,6))
plt.plot(list(price_hist.keys()), list(price_hist.values()))
plt.axvline(x=np.datetime64('2024-09-10'), color='grey', linestyle='-')
plt.axvline(x=np.datetime64('2024-09-11'), color='grey', linestyle='-')
plt.axvline(x=np.datetime64('2024-09-12'), color='grey', linestyle='-')
plt.axvline(x=np.datetime64('2024-09-13'), color='grey', linestyle='-')
plt.axvline(x=np.datetime64('2024-09-14'), color='grey', linestyle='-')
for i in range(steps+1):
  plt.axhline(y=price_of_level(i), color='grey', linestyle='-')
plt.show()

import pandas as pd
from datetime import timedelta

crypto_hist = {}

def trade(price_hist):

  global usdt
  global crypto
  global crypto_hist

  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

    # print(f"{dt}: {price}")
    previous_level = level
    level = level_of_price(price)
    previous_trend = trend

    #crypto_hist.append(crypto)
    #dt1 = pd.Timestamp(dt) #.to_datetime()
    #dt1 = pd.to_datetime(dt)
    #crypto_hist[dt1] = crypto

    if level < previous_level:
      trend = -1
      if trend == previous_trend:
        # print(f"{dt}: Ligne {level+1} franchie à la baisse : {previous_level} -> {level}")
        for i in range(previous_level, level, -1):
          nt = nt + 1
          trade_price = price_of_level(i)
          # Buy cryptos for order_amount USDT
          usdt = usdt - order_amount - fees
          crypto_hist[pd.Timestamp(dt) - pd.Timedelta(milliseconds=100)] = crypto
          crypto = crypto + order_amount / trade_price
          crypto_hist[dt] = crypto
          total = usdt + crypto * trade_price
          #crypto_hist.append(crypto)
          #crypto_hist[dt] = crypto
          print(f"{dt}: Ligne {i:3d} ({trade_price:9.2f} ) franchie à la baisse: {nt:3d} ACHAT -> USDT: {usdt:9.2f}, crypto: {crypto:9.6f}, total: {total:9.2f}")

    elif level > previous_level:
      trend = 1
      if trend == previous_trend:
        # print(f"{dt}: Ligne {level} franchie à la hausse : {previous_level} -> {level}")
        for i in range(previous_level, level):
          nt = nt + 1
          trade_price = price_of_level(i+1)
          # Sell cryptos for order_amount USDT
          usdt = usdt + order_amount - fees
          crypto_hist[pd.Timestamp(dt) - pd.Timedelta(milliseconds=100)] = crypto
          crypto = crypto - order_amount / trade_price
          crypto_hist[dt] = crypto
          total = usdt + crypto * trade_price
          #crypto_hist.append(crypto)
          #crypto_hist[dt] = crypto
          print(f"{dt}: Ligne {i+1:3d} ({trade_price:9.2f} ) franchie à la hausse: {nt:3d} VENTE -> USDT: {usdt:9.2f}, crypto: {crypto:9.6f}, total: {total:9.2f}")

trade(price_hist)

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