import os
import traceback
import pandas as pd
from datetime import datetime
import talib
import datetime
import numpy as np
import warnings
import ccxt
import polars as pl
import sys
warnings.filterwarnings('ignore')
pd.set_option('display.float_format', '{:.5f}'.format)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
Exchange = ccxt.binance()
Amount = 3
Leverage = 20
Fees = 0.16
ShortSaveThreshold = 2000
ALLTimeThreshHold = 0
back_date = '2020-12-01'
InfinityTimestamp = pd.to_datetime('2025-01-01')
ListOFDates = []
while True:
TotalProfit = []
AvailableCoins = []
OverALLYearProfit = []
TotalCoinsList = []
TotalDollarsList = []
TotalResultList = []
TotalBuyTimestamp = []
TotalHitTimestamp = []
TotalBuyAmountList = []
TotalTradeIdList = []
TradeTimestampList = []
TotalTradeNameList = []
AllCoinsDataFrameList = []
LiquidationTimestamps = []
TotalLiquidateTimestamp = []
if ListOFDates:
start_date = str(ListOFDates[-1])
else:
start_date = '2022-01-12 06:45:00'
end_date = str(pd.to_datetime(start_date)+datetime.timedelta(days=5))
def Saver(Coin,TimeFrame):
try:
folder_path = f'E:\\BinanceData\\monthlyfutures\\{Coin}\\{TimeFrame}\\'
merged_data = pd.DataFrame()
for file in os.listdir(folder_path):
if file.endswith('.csv'):
try:
if Coin in file:
CurrentDate = pd.to_datetime(f'{file.split("-")[2]}-{file.split("-")[3].replace(".csv", "")}-01')
if CurrentDate >= pd.to_datetime(back_date) and CurrentDate <= pd.to_datetime(end_date):
file_path = os.path.join(folder_path, file)
df = pd.read_csv(file_path, header=None)
if df.iloc[0].apply(lambda x: isinstance(x, (int, float))).all():
header_row = None
else:
header_row = 0
df = pd.read_csv(file_path, header=header_row)
df.columns = ['open_time', 'open', 'high', 'low', 'close', 'volume', 'close_time',
'quote_volume',
'count', 'taker_buy_volume', 'taker_buy_quote_volume', 'ignore']
df['Timestamp'] = pd.to_datetime(df['open_time'], unit='ms')
df = df.drop(columns=['open_time', 'close_time', 'quote_volume', 'count', 'taker_buy_volume',
'taker_buy_quote_volume', 'ignore'])
merged_data = merged_data.append(df, ignore_index=True)
except ValueError:
pass
def stochastic(data, k_window, d_window, window):
min_val = data.rolling(window=window, center=False).min()
max_val = data.rolling(window=window, center=False).max()
stoch = ((data - min_val) / (max_val - min_val)) * 100
K = stoch.rolling(window=k_window, center=False).mean()
D = K.rolling(window=d_window, center=False).mean()
return K, D
def Arranger(List):
LastAvailableTimestamp = pd.to_datetime('1989-01-01')
List = List[::-1]
for i in List:
if i != 0:
LastAvailableTimestamp = i
break
return pd.to_datetime(LastAvailableTimestamp)
def TPSLCalculatorLong(Data):
BuyTimestampList = []
HitTimestampList = []
ResultList = []
DollarsList = []
TradeNameList = []
for Timestamp,CurrentPrice in zip(Data['Timestamp'],Data['open']):
if Arranger(HitTimestampList) < pd.to_datetime(Timestamp):
FutureData = merged_data[merged_data['Timestamp'] >= Timestamp]
DipData = FutureData[(FutureData['DipL'] == True) | (FutureData['Timestamp'] == Timestamp)]
DipData['BuyPrice'] = DipData['open']
TimestampsTrue = []
BuyPricePrevious = 0
for BuyPrice, TimestampToTake in zip(DipData['BuyPrice'], DipData['Timestamp']):
if BuyPricePrevious == 0:
BuyPricePrevious = BuyPrice
TimestampsTrue.append(TimestampToTake)
else:
if BuyPricePrevious > BuyPrice:
BuyPricePrevious = BuyPrice
TimestampsTrue.append(TimestampToTake)
DipData = DipData[DipData['Timestamp'].isin(TimestampsTrue)]
previous_elements = []
for index, row in DipData.iterrows():
previous_elements_list = DipData.loc[:index, 'BuyPrice'].tolist()
previous_elements.append(previous_elements_list)
DipData['All_BuyPrices'] = previous_elements
DipTimestamps = list(DipData['Timestamp'])
NextDipTimestamps = list(DipData['Timestamp'].shift(-1))
return ResultList,DollarsList,BuyTimestampList,HitTimestampList,TradeNameList
YearList = []
for Timestamp in merged_data['Timestamp']:
YearList.append(Timestamp.year)
merged_data['EMA3'] = talib.EMA(merged_data['close'],10)
merged_data['EMA6'] = talib.EMA(merged_data['close'],20)
merged_data['Year'] = YearList
merged_data['CrossOverLong'] = (merged_data['Year'] == 2022)&(merged_data['EMA3'].shift(1) > merged_data['EMA6'].shift(1))&(merged_data['EMA3'].shift(2) < merged_data['EMA6'].shift(2))
merged_data['CrossOverShort'] = (merged_data['Year'] == 2022)&(merged_data['EMA3'].shift(1) < merged_data['EMA6'].shift(1))&(merged_data['EMA3'].shift(2) > merged_data['EMA6'].shift(2))
merged_data['DipL'] = (merged_data['close'].shift(1) > merged_data['high'].shift(2))
merged_data['DipH'] = (merged_data['close'].shift(1) < merged_data['low'].shift(2))
YearList = []
for Timestamp in merged_data['Timestamp']:
YearList.append(Timestamp.year)
merged_data['Year'] = YearList
merged_data = merged_data[["Timestamp"] + [col for col in merged_data.columns if col != "Timestamp"]]
merged_data['Coin'] = Coin
CrossOverDataLong = merged_data[(merged_data['CrossOverLong'] == True)&(merged_data['Timestamp'] >= pd.to_datetime(start_date))&(merged_data['Timestamp'] <= pd.to_datetime(end_date))]
CrossOverDataLong['PreviousTimestamp'] = CrossOverDataLong['Timestamp'].shift(1)
CrossOverDataLong['Result'],CrossOverDataLong['Dollars'],CrossOverDataLong['BuyTimestamps'],CrossOverDataLong['HitTimestamp'],CrossOverDataLong['TradeName'] = TPSLCalculatorLong(CrossOverDataLong)
CrossOverDataShort = merged_data[(merged_data['CrossOverLong'] == True) & (merged_data['Timestamp'] >= pd.to_datetime(start_date)) & (merged_data['Timestamp'] <= pd.to_datetime(end_date))]
CrossOverDataShort['PreviousTimestamp'] = CrossOverDataShort['Timestamp'].shift(1)
CrossOverDataShort['Result'], CrossOverDataShort['Dollars'], CrossOverDataShort['BuyTimestamps'], CrossOverDataShort['HitTimestamp'], CrossOverDataShort['TradeName'] = TPSLCalculatorShort(CrossOverDataShort)
CompleteData = pd.concat([CrossOverDataLong,CrossOverDataShort])
CrossOverDataLong = CompleteData
CrossOverDataLong['MaxBuy'] = 1
CrossOverDataLong = CrossOverDataLong[CrossOverDataLong['Result'] != 'Neutral']
LongTPS = CrossOverDataLong[CrossOverDataLong['Dollars'] >= 0]
LongSLS = CrossOverDataLong[CrossOverDataLong['Dollars'] <= 0]
Pct = []
for BuyTimestamps in CrossOverDataLong['BuyTimestamps']:
try:
FirstBuyTimestamp = BuyTimestamps[0]
LastBuyTimestamp = BuyTimestamps[-1]
FirstBuyPrice = merged_data[merged_data['Timestamp'] == FirstBuyTimestamp].iloc[-1]['open']
LastBuyPrice = merged_data[merged_data['Timestamp'] == LastBuyTimestamp].iloc[-1]['open']
MaxPct = abs(((LastBuyPrice - FirstBuyPrice) * 100) / FirstBuyPrice)
Pct.append(MaxPct)
except Exception as e:
Pct.append(0)
CrossOverDataLong['MaxPct'] = Pct
TotalProfit.append(sum(CrossOverDataLong['Dollars']))
print(CrossOverDataLong[['BuyTimestamps','HitTimestamp','Dollars','Result','MaxBuy','TradeName']])
print(f"Profit || Long:{sum(CrossOverDataLong['Dollars'])} || Coin:{Coin},TotalTP:{len(LongTPS)},TotalSL:{len(LongSLS)},MaxBuys:{max(CrossOverDataLong['MaxBuy'])},MaxPct:{max(CrossOverDataLong['MaxPct'])}")
AvailableCoins.append(Coin)
AllCoinsDataFrameList.append(merged_data)
for Result, Dollars, BuyTimestamps, HitTimestamp,Timestamp,TradeName in zip(CrossOverDataLong['Result'], CrossOverDataLong['Dollars'],CrossOverDataLong['BuyTimestamps'], CrossOverDataLong['HitTimestamp'],CrossOverDataLong['Timestamp'],CrossOverDataLong['TradeName']):
if TradeName == 'Long':
TotalCoinsList.append(Coin)
TotalResultList.append(Result)
TotalDollarsList.append(Dollars)
TotalBuyTimestamp.append(BuyTimestamps)
TotalHitTimestamp.append(HitTimestamp)
TotalBuyAmountList.append(Amount)
TotalTradeIdList.append(f'1 Entry')
TradeTimestampList.append(Timestamp)
TotalTradeNameList.append(TradeName)
elif TradeName == 'Short':
TotalCoinsList.append(Coin)
TotalResultList.append(Result)
TotalDollarsList.append(Dollars)
TotalBuyTimestamp.append(BuyTimestamps)
TotalHitTimestamp.append(HitTimestamp)
TotalBuyAmountList.append(Amount)
TotalTradeIdList.append(f'1 Entry')
TradeTimestampList.append(Timestamp)
TotalTradeNameList.append(TradeName)
except Exception as e:
traceback.print_exc()
with open("Future_ALL_Coins.txt", "r") as r:
# Lines = ['1000SHIBUSDT', '1000XECUSDT', '1INCHUSDT', 'AAVEUSDT', 'ADAUSDT', 'ALGOUSDT', 'ALICEUSDT', 'ALPHAUSDT', 'ANKRUSDT', 'ARPAUSDT', 'ARUSDT', 'ATAUSDT', 'ATOMUSDT', 'AUDIOUSDT', 'AVAXUSDT', 'AXSUSDT', 'BAKEUSDT', 'BALUSDT', 'BANDUSDT', 'BATUSDT', 'BCHUSDT', 'BELUSDT', 'BLZUSDT', 'BNBUSDT', 'BTCUSDT', 'C98USDT', 'CELOUSDT', 'CELRUSDT', 'CHRUSDT', 'CHZUSDT', 'COMPUSDT', 'COTIUSDT', 'CRVUSDT', 'CTKUSDT', 'CTSIUSDT', 'DASHUSDT', 'DEFIUSDT', 'DENTUSDT', 'DGBUSDT', 'DOGEUSDT', 'DOTUSDT', 'EGLDUSDT', 'ENJUSDT', 'EOSUSDT', 'ETCUSDT', 'ETHUSDT', 'FILUSDT', 'FLMUSDT', 'FTMUSDT', 'GALAUSDT', 'GRTUSDT', 'GTCUSDT', 'HBARUSDT', 'HNTUSDT', 'HOTUSDT', 'ICPUSDT', 'ICXUSDT', 'IOSTUSDT', 'IOTAUSDT', 'IOTXUSDT', 'KAVAUSDT', 'KLAYUSDT', 'KNCUSDT', 'KSMUSDT', 'LINAUSDT', 'LINKUSDT', 'LITUSDT', 'LPTUSDT', 'LRCUSDT', 'LTCUSDT', 'MANAUSDT', 'MASKUSDT', 'MATICUSDT', 'MKRUSDT', 'MTLUSDT', 'NEARUSDT', 'NEOUSDT', 'NKNUSDT', 'OCEANUSDT', 'OGNUSDT', 'OMGUSDT', 'ONEUSDT', 'ONTUSDT', 'QTUMUSDT', 'REEFUSDT', 'RENUSDT', 'RLCUSDT', 'RSRUSDT', 'RUNEUSDT', 'RVNUSDT', 'SANDUSDT', 'SFPUSDT', 'SKLUSDT', 'SNXUSDT', 'SOLUSDT', 'STMXUSDT', 'STORJUSDT', 'SUSHIUSDT', 'SXPUSDT', 'THETAUSDT', 'TLMUSDT', 'TOMOUSDT', 'TRBUSDT', 'TRXUSDT', 'UNFIUSDT', 'UNIUSDT', 'VETUSDT', 'WAVESUSDT', 'XEMUSDT', 'XLMUSDT', 'XMRUSDT', 'XRPUSDT', 'XTZUSDT', 'YFIUSDT', 'ZECUSDT', 'ZENUSDT', 'ZILUSDT', 'ZRXUSDT']
# Lines = ['1000SHIBUSDT', '1000XECUSDT', '1INCHUSDT', 'AAVEUSDT', 'ADAUSDT', 'ALGOUSDT', 'ALICEUSDT', 'ALPHAUSDT', 'ANKRUSDT', 'ARPAUSDT']
Lines = ['1INCHUSDT']
ThreadList = []
for Coin in Lines:
Coin = Coin.replace('\n', '')
Saver(Coin,'5m')
TotalDataFrame = pd.DataFrame({
'Symbol':TotalCoinsList,
'Result':TotalResultList,
'Dollars':TotalDollarsList,
'BuyTimestamp':TotalBuyTimestamp,
'HitTimestamp':TotalHitTimestamp,
'TotalBuyAmount':TotalBuyAmountList,
'Timestamp':TradeTimestampList,
'TradeName':TotalTradeNameList,
})
TotalDataFrame['HitTimestamp'] = pd.to_datetime(TotalDataFrame['HitTimestamp'])
TotalDataFrame['BuyTimestamp'] = pd.to_datetime(TotalDataFrame['BuyTimestamp'])
TotalDataFrame.to_csv("E:\\LongShort(AccountDouble)(TD).csv")
AllCoinsDataFrame = pd.concat(AllCoinsDataFrameList)
AllCoinsDataFrame.to_csv("E:\\LongShort(AccountDouble)(ACD).csv")
AmountLong = 3
AmountShort = 3
Leverage = 20
InfinityTimestamp = '2025-01-01'
def unrealized_pnl(buy_timestamps,BuyAmountDollars, current_timestamps, coins, all_coins_dataframe, trade_types):
try:
all_coins_dataframe = all_coins_dataframe.to_pandas()
all_coins_dataframe_reset = all_coins_dataframe.reset_index()
DataCheck = all_coins_dataframe_reset.merge(pd.DataFrame({'Timestamp': buy_timestamps, 'Coin': coins, 'TradeName': trade_types}),on=['Timestamp', 'Coin'])
indexes_dropped = DataCheck.index
DataCheck = DataCheck.drop_duplicates()
indexes_dropped = indexes_dropped.difference(DataCheck.index)
DataCheckCurrent = all_coins_dataframe_reset.merge(pd.DataFrame({'Timestamp': current_timestamps, 'Coin': coins, 'TradeName': trade_types}),on=['Timestamp', 'Coin'])
DataCheckCurrent = DataCheckCurrent.drop(indexes_dropped)
ListNoCandleCoins = list(set(list(DataCheck['Coin'])) - set(list(DataCheckCurrent['Coin'])))
DataCheck = DataCheck[~DataCheck['Coin'].isin(ListNoCandleCoins)]
DataCheck.reset_index(inplace=True)
buy_prices = list(DataCheck['open'])
buy_prices = np.array(buy_prices)
Trade_types = list(DataCheck['TradeName'])
Trade_types = np.array(Trade_types)
Lowcurrent_prices = list(DataCheckCurrent['low'])
Lowcurrent_prices = np.array(Lowcurrent_prices)
Highcurrent_prices = list(DataCheckCurrent['high'])
Highcurrent_prices = np.array(Highcurrent_prices)
pctLow = np.abs((Lowcurrent_prices - buy_prices) * 100 / buy_prices)
pctHigh = np.abs((Highcurrent_prices - buy_prices) * 100 / buy_prices)
trade_amountLong = AmountLong * Leverage
trade_amountShort = AmountShort * Leverage
total_dollars = np.array(np.zeros(len(buy_timestamps)))
Profit_long_condition = np.where(((Trade_types == 'Long')|(Trade_types == 'LongDouble')) & (Lowcurrent_prices > buy_prices))
loss_long_condition = np.where(((Trade_types == 'Long')|(Trade_types == 'LongDouble')) & (Lowcurrent_prices <= buy_prices))
Profit_short_condition = np.where(((Trade_types == 'Short')|(Trade_types == 'ShortDouble')) & (Highcurrent_prices < buy_prices))
loss_short_condition = np.where(((Trade_types == 'Short')|(Trade_types == 'ShortDouble')) & (Highcurrent_prices >= buy_prices))
total_dollars[Profit_long_condition] = trade_amountLong
total_dollars[Profit_long_condition] += total_dollars[Profit_long_condition] * pctLow[Profit_long_condition] / 100
total_dollars[Profit_long_condition] = total_dollars[Profit_long_condition] - trade_amountLong
total_dollars[Profit_short_condition] = trade_amountShort
total_dollars[Profit_short_condition] += total_dollars[Profit_short_condition] * pctHigh[Profit_short_condition] / 100
total_dollars[Profit_short_condition] = total_dollars[Profit_short_condition] - trade_amountShort
total_dollars[loss_long_condition] = trade_amountLong
total_dollars[loss_long_condition] -= total_dollars[loss_long_condition] * pctLow[loss_long_condition] / 100
total_dollars[loss_long_condition] = total_dollars[loss_long_condition] - trade_amountLong
total_dollars[loss_short_condition] = trade_amountShort
total_dollars[loss_short_condition] -= total_dollars[loss_short_condition] * pctHigh[loss_short_condition] / 100
total_dollars[loss_short_condition] = total_dollars[loss_short_condition] - trade_amountShort
####################################################### CLOSE #######################################################
Closecurrent_prices = list(DataCheckCurrent['close'])
Closecurrent_prices = np.array(Closecurrent_prices)
pctClose = np.abs((Closecurrent_prices - buy_prices) * 100 / buy_prices)
total_dollarsClose = np.array(np.zeros(len(buy_timestamps)))
Profit_long_condition = np.where(((Trade_types == 'Long')|(Trade_types == 'LongDouble')) & (Closecurrent_prices > buy_prices))
loss_long_condition = np.where(((Trade_types == 'Long')|(Trade_types == 'LongDouble')) & (Closecurrent_prices <= buy_prices))
Profit_short_condition = np.where(((Trade_types == 'Short')|(Trade_types == 'ShortDouble')) & (Closecurrent_prices < buy_prices))
loss_short_condition = np.where(((Trade_types == 'Short')|(Trade_types == 'ShortDouble')) & (Closecurrent_prices >= buy_prices))
total_dollarsClose[Profit_long_condition] = trade_amountLong
total_dollarsClose[Profit_long_condition] += total_dollarsClose[Profit_long_condition] * pctClose[Profit_long_condition] / 100
total_dollarsClose[Profit_long_condition] = total_dollarsClose[Profit_long_condition] - trade_amountLong
total_dollarsClose[Profit_short_condition] = trade_amountShort
total_dollarsClose[Profit_short_condition] += total_dollarsClose[Profit_short_condition] * pctClose[Profit_short_condition] / 100
total_dollarsClose[Profit_short_condition] = total_dollarsClose[Profit_short_condition] - trade_amountShort
total_dollarsClose[loss_long_condition] = trade_amountLong
total_dollarsClose[loss_long_condition] -= total_dollarsClose[loss_long_condition] * pctClose[loss_long_condition] / 100
total_dollarsClose[loss_long_condition] = total_dollarsClose[loss_long_condition] - trade_amountLong
total_dollarsClose[loss_short_condition] = trade_amountShort
total_dollarsClose[loss_short_condition] -= total_dollarsClose[loss_short_condition] * pctClose[loss_short_condition] / 100
total_dollarsClose[loss_short_condition] = total_dollarsClose[loss_short_condition] - trade_amountShort
except Exception as e:
traceback.print_exc()
return np.zeros(len(buy_timestamps)), np.zeros(len(buy_timestamps))
return total_dollars, total_dollarsClose
def process_intervals(interval_chunk, TotalDataFrame, AllCoinsDataFrame):
portfoilio = []
UnrealizedMax = []
MaxTotalDollars = []
total_dollars = 3000
HittedSymbols = []
SymbolListFirst = []
for candle_time in interval_chunk:
buy_data = TotalDataFrame.filter(TotalDataFrame['BuyTimestamp'] == pd.to_datetime(candle_time))
buy_data = buy_data.to_pandas()
buy_data = buy_data[~(buy_data['Symbol'].isin(HittedSymbols))]
hit_data = TotalDataFrame.filter(TotalDataFrame['HitTimestamp'] == pd.to_datetime(candle_time))
not_hit_data = TotalDataFrame.filter((TotalDataFrame['BuyTimestamp'] <= pd.to_datetime(candle_time)) & (TotalDataFrame['HitTimestamp'] > pd.to_datetime(candle_time)) & (TotalDataFrame['HitTimestamp'] != pd.to_datetime(candle_time)))
not_hit_data = not_hit_data.to_pandas()
not_hit_data = not_hit_data[~not_hit_data['Symbol'].isin(HittedSymbols)]
hit_data = hit_data.to_pandas()
if not SymbolListFirst:
for Symbol in buy_data['Symbol']:
SymbolListFirst.append(Symbol)
else:
buy_data = buy_data[buy_data['Symbol'].isin(SymbolListFirst)]
hit_data = hit_data[hit_data['Symbol'].isin(SymbolListFirst)]
not_hit_data = not_hit_data[not_hit_data['Symbol'].isin(SymbolListFirst)]
not_hit_data['candle_time'] = candle_time
not_hit_data['Fees'] = (not_hit_data['TotalBuyAmount']*Leverage)
not_hit_data['Fees'] -= not_hit_data['Fees'] * 0.16 / 100
not_hit_data['Fees'] = not_hit_data['Fees'] - (not_hit_data['TotalBuyAmount']*Leverage)
not_hit_data = not_hit_data.sort_values(by='Symbol')
print(f"InTradeSymbols:{SymbolListFirst}")
HitList = []
ChunkList = []
if not not_hit_data.empty:
not_hit_data['UnrealizedPnlHL'], not_hit_data['UnrealizedPnlClose'] = unrealized_pnl(not_hit_data['BuyTimestamp'],not_hit_data['TotalBuyAmount'], not_hit_data['candle_time'], not_hit_data['Symbol'],AllCoinsDataFrame, not_hit_data['TradeName'])
not_hit_data['UnrealizedPnlHL'] = not_hit_data['Fees']+not_hit_data['UnrealizedPnlHL']
not_hit_data['UnrealizedPnlClose'] = not_hit_data['Fees']+not_hit_data['UnrealizedPnlClose']
not_hit_dataChunks = [group for _, group in not_hit_data.groupby('Symbol')]
for chunk in not_hit_dataChunks:
if sum(chunk['UnrealizedPnlClose']) > 0.02:
HitList.append(chunk.iloc[-1]['Symbol'])
ChunkList.append(chunk)
HittedSymbols.append(chunk.iloc[-1]['Symbol'])
if chunk.iloc[-1]['Symbol'] in SymbolListFirst:
SymbolListFirst.remove(chunk.iloc[-1]['Symbol'])
not_hit_data = not_hit_data[~not_hit_data['Symbol'].isin(HitList)]
total_unrealized_pnl = sum(not_hit_data['UnrealizedPnlHL'])
total_unrealized_pnlClose = sum(not_hit_data['UnrealizedPnlClose'])
else:
total_unrealized_pnl = 0
total_unrealized_pnlClose = 0
for chunk in ChunkList:
chunk['Dollars'] = chunk['UnrealizedPnlClose']
chunk['HitTimestamp'] = candle_time
hit_data = pd.concat([hit_data, chunk[['', 'Symbol', 'Result', 'Dollars', 'BuyTimestamp', 'HitTimestamp', 'TotalBuyAmount', 'Timestamp','TradeName']]], axis=0)
for BuyTimestamp in chunk['BuyTimestamp']:
TotalDataFrame = TotalDataFrame.with_columns((pl.when((pl.col('Symbol') == chunk.iloc[-1]['Symbol'])&(pl.col('BuyTimestamp') == BuyTimestamp)).then(pl.lit(candle_time)).otherwise(pl.col('HitTimestamp'))).alias('HitTimestamp'))
total_dollars = total_dollars - sum(buy_data['TotalBuyAmount'])
TotalDollarsHit = 0
Profit = 0
for Dollar, TotalBuyAmount in zip(hit_data['Dollars'], hit_data['TotalBuyAmount']):
Profit += Dollar
TotalDollarsHit += TotalBuyAmount
total_dollars = total_dollars + TotalDollarsHit
total_dollars = total_dollars + Profit
WalletOverviewHL = total_dollars + sum(not_hit_data['TotalBuyAmount']) + total_unrealized_pnl
WalletOverviewClose = total_dollars + sum(not_hit_data['TotalBuyAmount']) + total_unrealized_pnlClose
if total_unrealized_pnl > 0:
AvailableBalance = total_dollars
AvailableBalanceClose = total_dollars
else:
AvailableBalance = total_dollars + total_unrealized_pnl
AvailableBalanceClose = total_dollars + total_unrealized_pnlClose
print(f" (High-Low) || Timestamp:{candle_time},WalletOverview:{WalletOverviewHL},AvailableBalance:{AvailableBalance},UPNL:{total_unrealized_pnl},InTradeDollars:{sum(not_hit_data['TotalBuyAmount'])}")
print(f" (Close) || (Timestamp):{candle_time},(WalletOverview):({WalletOverviewClose}),(AvailableBalance):({AvailableBalanceClose}),(UPNL):({total_unrealized_pnlClose}),(InTradeDollars):({sum(not_hit_data['TotalBuyAmount'])})")
portfoilio.append(AvailableBalance)
UnrealizedMax.append(total_unrealized_pnl)
MaxTotalDollars.append(sum(not_hit_data['TotalBuyAmount']))
if WalletOverviewClose > 3000:
print(f'CloseTime = {candle_time} || Profit = {WalletOverviewClose-3000} || MinPortfolio = {min(portfoilio)} || UnrealizedPnlMax = {min(UnrealizedMax)} || Duration:{candle_time-pd.to_datetime(start_date)}')
restorePoint = sys.stdout
sys.stdout = sys.stdout
sys.stdout = open("LongShort(AccountDouble).txt", "a")
print(f'CloseTime = {candle_time} || Profit = {WalletOverviewClose-3000} || MinPortfolio = {min(portfoilio)} || UnrealizedPnlMax = {min(UnrealizedMax)} Duration:{candle_time-pd.to_datetime(start_date)}')
sys.stdout.close()
sys.stdout = restorePoint
ListOFDates.append(candle_time+datetime.timedelta(minutes=5))
break
if __name__ == "__main__":
TotalDataFrame = pl.read_csv("E:\\LongShort(AccountDouble)(TD).csv", try_parse_dates=True)
AllCoinsDataFrame = pl.read_csv("E:\\LongShort(AccountDouble)(ACD).csv", try_parse_dates=True)
AllCoinsDataFrame = AllCoinsDataFrame.select(
pl.col("Timestamp"),
pl.col("Coin"),
pl.col("open").cast(pl.Float32),
pl.col("high").cast(pl.Float32),
pl.col("low").cast(pl.Float32),
pl.col("close").cast(pl.Float32),
pl.col("volume").cast(pl.Float32),
)
TotalDataFrame = TotalDataFrame.sort('BuyTimestamp')
TotalDataFrame = TotalDataFrame.drop('index')
four_hour_intervals = pd.date_range(start=start_date, end=str(pd.to_datetime(start_date)+datetime.timedelta(days=500)), freq='5T')
process_intervals(four_hour_intervals, TotalDataFrame, AllCoinsDataFrame)
I Want to exit the coin when it is in profit of 0.02 dollars....
But iam trying from since 1day as iam a beginner in python i dont know how to write the code well.
Please guide me how to do this.
Acutually i am calculating the unrealized pnl of my strategy.
Is my code too complicated?
have i wrote the correct code.
Or i have to more improve my coding python