import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# Parameters
D = 10     # Distance
I_L = 0.01 # Initial Lot Size
M = 2      # Lot Size Multiplier
S = 1      # Spread
T_P = 50   # Take Profit

# Values of x to evaluate
x_values = range(1, 21)  # x from 1 to 20

def g(x, I_L, M):
    return np.floor(I_L * 100 * M ** x)

def s(x, I_L, M, S):
    return sum(g(i, I_L, M) * S for i in range(x))

def t(x, D, I_L, M, T_P):
    numerator = sum(i * g(i, I_L, M) for i in range(x)) * D
    denominator = sum(g(i, I_L, M) for i in range(x))
    return (numerator / denominator) - T_P

def p(x, D, I_L, M, S, T_P):
    return sum(g(i, I_L, M) * (i * D - t(x, D, I_L, M, T_P)) for i in range(x)) - s(x, I_L, M, S)

def c(x, D, I_L, M, S):
    return D * sum(g(i, I_L, M) * (x - i) for i in range(x)) + s(x, I_L, M, S)

# Calculate p(x) and c(x) for each x
p_values = [p(x, D, I_L, M, S, T_P) for x in x_values]
c_values = [c(x, D, I_L, M, S) for x in x_values]

# Formatter to avoid exponential notation
def format_func(value, tick_number):
    return f'{value:.2f}'

# Plotting
fig, axs = plt.subplots(2, 1, figsize=(12, 12))

# Combined plot for p(x) and c(x)
axs[0].plot(x_values, p_values, label='p(x)', marker='o')
axs[0].plot(x_values, c_values, label='c(x)', marker='o', color='orange')
axs[0].set_title('p(x) and c(x) vs x')
axs[0].set_xlabel('x')
axs[0].set_ylabel('Values')
axs[0].set_xticks(x_values)
axs[0].grid(True)
axs[0].legend()
axs[0].yaxis.set_major_formatter(FuncFormatter(format_func))

# Create table data
table_data = [['x', 'p(x)', 'c(x)']] + [[x, f'{p_val:.2f}', f'{c_val:.2f}'] for x, p_val, c_val in zip(x_values, p_values, c_values)]

# Plot table
axs[1].axis('tight')
axs[1].axis('off')
table = axs[1].table(cellText=table_data, cellLoc='center', loc='center')
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1.2, 1.2)

plt.tight_layout()
plt.show()
