-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrading_calculators.py
More file actions
237 lines (181 loc) · 6.93 KB
/
Copy pathtrading_calculators.py
File metadata and controls
237 lines (181 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import argparse
# Percentage Return
def percentage_return(entry_price: float, exit_price: float) -> float:
"""Calculate the percentage return of an invesment.
Formula: ((exit_price - entry_price) / entry_price) * 100
Args:
entry_price: The initial price you bought at.
exit_price: The current or selling price.
Returns:
The percentage return. Positive means profit, negative means loss.
Raises:
ValueError: if entry_price is zero(cannot divide by zero).
"""
if entry_price == 0:
raise ValueError("entry_price cannot be zero.")
return (exit_price - entry_price) / entry_price * 100
# Trading Fees
def total_fees(
entry_price: float,
exit_price: float,
fee_rate: float,
quantity: float = 1.0,
) -> float:
"""Calculate the round-trip trading fees for a position.
Round-trip means you pay a fee once when entring and once when exiting.
Formula:
notional = price * quantity
total_fees: (entry_notional * fee_rate) + (exit_notional * fee_rate)
Args:
entry_price: Price per unit when entering the trade.
exit_price: Price per unit when exiting the trade.
fee_rate: Fee as a decimal (e.g. 0.001 for 0.1%)
quantity: Number of units traded. Defaults to 1.
Returns:
The total fees paid across entry and exit.
Raises:
ValueError: if any value is negative.
"""
if entry_price < 0 or exit_price < 0:
raise ValueError("Prices cannot be negative.")
if fee_rate < 0:
raise ValueError("fee_rate cannot be negative.")
if quantity < 0:
raise ValueError("quantity cannot be negative.")
entry_notional = entry_price * quantity
exit_notional = exit_price * quantity
return (entry_notional * fee_rate) + (exit_notional * fee_rate)
# Position-sizing
def position_size(
account_balance: float,
risk_per_trade: float,
entry: float,
stop_loss: float,
) -> float:
"""Calculate position size in units for a trade.
Formula:
risk_amount = acoount_balance * (risk_per_trade / 100)
risk_per_unit = abs(entry - stop loss)
position_size = risk_amount / risk_per_unit
Args:
account_balance: Total trading capital.
risk_per_trade: Percentage of balance to risk, e.g. 1 for 1%.
entry: Planned entry price.
stop loss: Price where you exit to cap your loss.
Returns:
Position size in units (not dollars).
Rasies:
ValueError: if entry equals stop_loss (risk per unit is zero),
or if any input is invalid.
"""
if account_balance <= 0:
raise ValueError("account_balance must be positive.")
if risk_per_trade <= 0:
raise ValueError("risk_per_trade must be positive.")
if entry == stop_loss:
raise ValueError("entry and stop_loss cannot be equal (risk per unit is zero).")
risk_amount = account_balance * (risk_per_trade / 100)
risk_per_unit = abs(entry - stop_loss)
return risk_amount / risk_per_unit
# Reward-to-Risk
def calculate_reward_risk_ratio(
entry: float,
stop_loss: float,
take_profit: float,
) -> float:
"""Caculate the Reward-to-Risk ratio for a long trade.
Formula:
reward = take_profit - entry
risk = entry - stop loss
ratio = reward / risk
Args:
entry: The price at which the position is opened.
stop_loss: The price at which the trade is closed at a loss.
Must be below entry for a long trade.
take_profit: The target price to close at a profit.
Must be above entry for a long trade.
Returns:
The reward-to-risk ratio.
Raises:
ValueError: if stop_loss >= entry or take_profit <= entry.
"""
if stop_loss >= entry:
raise ValueError("stop_loss must be below entry for a long trade.")
if take_profit <= entry:
raise ValueError("take_profit must be above entry for a long trade.")
reward = take_profit - entry
risk = entry - stop_loss
return reward / risk
# Stop-loss Distance
def stop_loss_distance(entry: float, stop_loss: float) -> dict[str, float]:
"""Calculate the distance between entry and stop-loss.
Formula:
absolute = abs(entry - stop_loss)
percent = (absolute / entry) * 100
Args:
entry: The entry price of the trade.
stop_loss: The stop-loss price.
Returns:
A Dict with 'absolute' (price difference) and 'percent'
(distance as a percentage of entry). works for long and short.
Raises:
ValueError: if entry is not positive, or stop_loss is negative.
"""
if entry <= 0:
raise ValueError("entry must be positive.")
if stop_loss < 0:
raise ValueError("stop_loss cannot be negative.")
absolute = abs(entry - stop_loss)
percent = (absolute / entry) * 100
return {"absolute": absolute, "percent": percent}
# Liquidation Price
def liquiadtion_price(
entry: float,
leverage: float,
is_long: bool = True,
) -> float:
"""Estimate the liquidation price of a leveraged position.
Formula:
move_fraction = 1 / leverage
long -> entry * (1 - move_fraction)
short -> entry * (1 + move_fraction)
Args:
entry: The entry price of the position.
leverage: The leverage multiplier (10 for 10x).
is_long: True for a long position, False for a short.
Returns:
The estimated liquidation price.
Raises:
ValueError: if entry is not positive, or leverage is not above 1.
"""
if entry <= 0:
raise ValueError("entry must be positive.")
if leverage <= 1:
raise ValueError("leverage must be greater thant 1.")
move_fraction = 1 / leverage
if is_long:
return entry * (1 - move_fraction)
return entry * (1 + move_fraction)
# CLI
def main() -> None:
parser = argparse.ArgumentParser(description="Trading calculators")
subparsers = parser.add_subparsers(dest="command", required=True)
sl = subparsers.add_parser("stop-distance", help="Stop-loss distance")
sl.add_argument("--entry", type=float, required=True)
sl.add_argument("--stop-loss", type=float, required=True)
liq = subparsers.add_parser("liquidation", help="Estimate liquidation price")
liq.add_argument("--entry", type=float, required=True)
liq.add_argument("--leverage", type=float, required=True)
liq.add_argument("--short", action="store_true", help="Short position")
args = parser.parse_args()
try:
if args.command == "stop-distance":
result = stop_loss_distance(args.entry, args.stop_loss)
print(f"Distance: {result['absolute']:.4f} ({result['percent']:.2f}%)")
elif args.command == "liquidation":
price = liquiadtion_price(args.entry, args.leverage, is_long=not args.short)
print(f"Estimated liquidation price: {price:.4f}")
except ValueError as e:
parser.error(str(e))
if __name__ == "__main__":
main()