-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpips_risk_language.py
More file actions
201 lines (167 loc) · 6.22 KB
/
Copy pathpips_risk_language.py
File metadata and controls
201 lines (167 loc) · 6.22 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
from __future__ import annotations
import argparse
import os
import re
from dataclasses import dataclass
from typing import Dict
class PipLangError(Exception):
pass
@dataclass
class InstrumentSpec:
pip_size: float
contract_size: float
@dataclass
class TradeCommand:
symbol: str
order_type: str
entry: float
sl: float
leverage: float
lot: float
INSTRUMENTS: Dict[str, InstrumentSpec] = {
"XAUUSD": InstrumentSpec(pip_size=0.01, contract_size=100.0),
"EURUSD": InstrumentSpec(pip_size=0.0001, contract_size=100000.0),
"GBPUSD": InstrumentSpec(pip_size=0.0001, contract_size=100000.0),
"USDJPY": InstrumentSpec(pip_size=0.01, contract_size=100000.0),
}
COMMAND_PATTERN = re.compile(
r"^\s*(?P<symbol>[A-Za-z]{6})\s+"
r"(?P<order_type>buy\s+limit|sell\s+limit|buy|sell)\s+"
r"(?P<entry>\d+(?:\.\d+)?)\s+"
r"sl\s+(?P<sl>\d+(?:\.\d+)?)\s+"
r"leverage\s+(?P<leverage>\d+(?:\.\d+)?)"
r"(?:\s+lot\s+(?P<lot>\d+(?:\.\d+)?))?\s*$",
re.IGNORECASE,
)
def parse_command(text: str) -> TradeCommand:
m = COMMAND_PATTERN.match(text)
if not m:
raise PipLangError(
"Invalid syntax. Use: '<SYMBOL> <buy limit|sell limit|buy|sell> "
"<ENTRY> sl <SL> leverage <LEV> [lot <LOT>]'."
)
symbol = m.group("symbol").upper()
order_type = " ".join(m.group("order_type").lower().split())
entry = float(m.group("entry"))
sl = float(m.group("sl"))
leverage = float(m.group("leverage"))
lot_raw = m.group("lot")
lot = float(lot_raw) if lot_raw else 1.0
if leverage <= 0:
raise PipLangError("Leverage must be greater than 0.")
if lot <= 0:
raise PipLangError("Lot size must be greater than 0.")
return TradeCommand(
symbol=symbol,
order_type=order_type,
entry=entry,
sl=sl,
leverage=leverage,
lot=lot,
)
def evaluate_trade(cmd: TradeCommand) -> Dict[str, float | str]:
if cmd.symbol not in INSTRUMENTS:
supported = ", ".join(sorted(INSTRUMENTS))
raise PipLangError(
f"Unsupported symbol '{cmd.symbol}'. "
f"Supported symbols: {supported}"
)
spec = INSTRUMENTS[cmd.symbol]
price_diff = abs(cmd.entry - cmd.sl)
pips = price_diff / spec.pip_size
# Position economics (for quote-currency P/L approximation):
# loss = price move * contract size * lots
loss_quote = price_diff * spec.contract_size * cmd.lot
notional = cmd.entry * spec.contract_size * cmd.lot
margin_required = notional / cmd.leverage
loss_on_margin_pct = (
(loss_quote / margin_required) * 100 if margin_required else 0.0
)
return {
"symbol": cmd.symbol,
"order_type": cmd.order_type,
"entry": cmd.entry,
"sl": cmd.sl,
"price_to_sl": price_diff,
"pip_size": spec.pip_size,
"pips_to_sl": pips,
"lot": cmd.lot,
"contract_size": spec.contract_size,
"leverage": cmd.leverage,
"position_notional": notional,
"margin_required": margin_required,
"sl_loss_quote": loss_quote,
"sl_loss_on_margin_pct": loss_on_margin_pct,
}
def run_pips_language(command_text: str) -> Dict[str, float | str]:
cmd = parse_command(command_text)
return evaluate_trade(cmd)
def run_prl_file(
file_path: str,
) -> list[tuple[int, str, Dict[str, float | str]]]:
results: list[tuple[int, str, Dict[str, float | str]]] = []
with open(file_path, "r", encoding="utf-8") as f:
for line_no, raw_line in enumerate(f, start=1):
line = raw_line.strip()
# Ignore blank lines and comment lines in .prl source files.
if not line or line.startswith("#"):
continue
result = run_pips_language(line)
results.append((line_no, line, result))
if not results:
raise PipLangError("No executable PRL commands found in file.")
return results
def pretty_report(result: Dict[str, float | str]) -> str:
return (
"PIP-RISK REPORT\n"
f"Symbol: {result['symbol']}\n"
f"Order Type: {result['order_type']}\n"
f"Entry: {result['entry']:.5f}\n"
f"SL: {result['sl']:.5f}\n"
f"Price Distance to SL: {result['price_to_sl']:.5f}\n"
f"Pips to SL: {result['pips_to_sl']:.2f} pips\n"
f"Leverage: 1:{result['leverage']:.0f}\n"
f"Lot Size: {result['lot']:.2f}\n"
f"Notional Position: {result['position_notional']:.2f}\n"
f"Required Margin: {result['margin_required']:.2f}\n"
f"Loss at SL (quote): {result['sl_loss_quote']:.2f}\n"
f"SL Loss as % of Margin: {result['sl_loss_on_margin_pct']:.2f}%"
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="PRL (Pips Risk Language) runner"
)
parser.add_argument("source", nargs="?", help="Path to a .prl file")
parser.add_argument("--command", help="Run a single inline PRL command")
args = parser.parse_args()
try:
if args.command:
output = run_pips_language(args.command)
print(f"INPUT: {args.command}")
print(pretty_report(output))
elif args.source:
file_results = run_prl_file(args.source)
for line_no, line, output in file_results:
print(f"LINE {line_no}: {line}")
print(pretty_report(output))
print("-" * 50)
else:
default_source = "pips_demo.prl"
if os.path.exists(default_source):
file_results = run_prl_file(default_source)
for line_no, line, output in file_results:
print(f"LINE {line_no}: {line}")
print(pretty_report(output))
print("-" * 50)
else:
demo_examples = [
"XAUUSD buy limit 3110.00 sl 3109.95 leverage 100",
"EURUSD buy 1.0900 sl 1.0880 leverage 50 lot 0.2",
]
for ex in demo_examples:
output = run_pips_language(ex)
print(f"INPUT: {ex}")
print(pretty_report(output))
print("-" * 50)
except PipLangError as err:
print(f"ERROR: {err}")