Skip to content

Instantly share code, notes, and snippets.

@3cBotPlus
Last active September 11, 2022 19:22
Show Gist options
  • Save 3cBotPlus/f1a0e58a6c6211f91e1dcedec7d2900d to your computer and use it in GitHub Desktop.
Save 3cBotPlus/f1a0e58a6c6211f91e1dcedec7d2900d to your computer and use it in GitHub Desktop.
Transform Trades List exported by TradingView into a 3Commas Deals List
### IMPORTANT THIS CODE IS OUTDATED!!!!
### PLEASE USE THE AWK SCRIPT FROM VERSION 3cBotPlus 6beta
# -*- coding: utf-8 -*-
# Author - hBroker at 3cBotPlus
# www.3cbotplus.com
# For MAC users: You need install before:
# xcode-select --install
# This script requires: pandas argparse tabulate
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse,os
import pandas as pd
from tabulate import tabulate
parser = argparse.ArgumentParser(description="Reorganize a Trade List into a Deal List")
parser.add_argument('--input', '-i', help='input file', required=False)
args = parser.parse_args()
input_file = args.input
deals_all = os.path.splitext(input_file)[0] + ".deals.csv"
deals_resume = os.path.splitext(input_file)[0] + ".deals.resume.csv"
# header=0 is default and means with name labels
trades = pd.read_csv(input_file)
trades.drop(trades.iloc[:, 6:], inplace = True, axis = 1)
# Fields extracting from column 2('Signal')
def getSO():
return int(trades.iloc[i,2].split(".")[2].split("#")[1])
def getDnum():
return int(trades.iloc[i,2].split(".")[0].split("#")[1])
def getEntryType():
return trades.iloc[i,2].split(".")[1]
deals = pd.DataFrame(columns = ['Deal','Duration','Safety Orders'])
DealNumber = 0
SOnumber = 0
DealStart = pd.Timestamp(trades.iloc[0,3]) #Date/Time col
BeginPeriod = pd.Timestamp(trades.iloc[0,3])
TotalDuration = BeginPeriod - DealStart
#TotalProfit =
for i in range(0,len(trades)):
if trades.iloc[i,2]=='Open': deals.drop(DealNumber-1)
else:
if getDnum()>DealNumber and getEntryType()=="Entry":
DealNumber = getDnum() # Update DealCounter
SOnumber = 0 # Update SO number
DealStart = pd.Timestamp(trades.iloc[i,3])
elif getEntryType()=="Exit" and getSO()>=SOnumber :
DealEnd = pd.Timestamp(trades.iloc[i,3])
Duration = (DealEnd - DealStart).total_seconds()/3600
SOnumber = getSO()
deals.loc[DealNumber]=([DealNumber,Duration,'SO'+str(SOnumber)])
TotalDuration = DealStart - BeginPeriod
grouped_SO = deals.groupby('Safety Orders').agg({'Safety Orders':['count'],'Duration': ['mean','median', 'min', 'max']})
grouped_SO.columns = ['qty','mean(h)', 'median(h)','min(h)', 'max(h)']
grouped_SO.insert(5, "max(d)",round(grouped_SO['max(h)']/24,1) , True)
grouped_SO.insert(1, "qty(%)",100*round(grouped_SO['qty']/len(deals),2) , True)
grouped_SO['mean(h)'] = grouped_SO['mean(h)'].apply(lambda x: round(x,1))
grouped_SO['min(h)'] = grouped_SO['min(h)'].apply(lambda x: round(x,1))
grouped_SO['max(h)'] = grouped_SO['max(h)'].apply(lambda x: round(x,1))
grouped_SO['median(h)'] = grouped_SO['median(h)'].apply(lambda x: round(x,1))
print("Total Duration: ",TotalDuration)
print("Total closed trades: ",len(trades)/2)
print("Total deals: ", len(deals))
print(tabulate(grouped_SO, headers='keys', tablefmt='psql'))
deals.to_csv(deals_all, index=False, encoding='utf-8')
grouped_SO.to_csv(deals_resume, index=False, encoding='utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment