-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3312 lines (2744 loc) · 139 KB
/
server.py
File metadata and controls
3312 lines (2744 loc) · 139 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Pine Script Library - Flask API Server
Provides CRUD operations for managing Pine Script metadata
"""
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
from datetime import datetime
import uuid
import re
import shutil
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
CORS(app) # Enable CORS for all routes
# Configuration
DATA_FILE = 'data/scripts.json'
BACKUP_DIR = 'data/backups'
# LLM Configuration
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
DEFAULT_LLM_PROVIDER = os.getenv('DEFAULT_LLM_PROVIDER', 'openai')
OPENAI_MODEL = os.getenv('OPENAI_MODEL', 'gpt-4')
CLAUDE_MODEL = os.getenv('CLAUDE_MODEL', 'claude-3-5-sonnet-20241022')
# Ensure backup directory exists
os.makedirs(BACKUP_DIR, exist_ok=True)
def load_scripts():
"""Load scripts from JSON file"""
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
return {"scripts": []}
except json.JSONDecodeError:
print(f"Error: Invalid JSON in {DATA_FILE}")
return {"scripts": []}
def save_scripts(data, create_backup=True):
"""Save scripts to JSON file with optional backup"""
# Create backup before saving (only if requested and file exists)
if create_backup and os.path.exists(DATA_FILE):
# Check if enough time has passed since last backup (avoid backup spam)
backups = sorted([f for f in os.listdir(BACKUP_DIR) if f.startswith('scripts_')])
should_backup = True
if backups:
# Get timestamp of most recent backup
last_backup = backups[-1]
last_backup_time = datetime.strptime(last_backup.replace('scripts_', '').replace('.json', ''), '%Y%m%d_%H%M%S')
time_since_backup = (datetime.now() - last_backup_time).total_seconds()
# Only create backup if more than 5 minutes have passed
should_backup = time_since_backup > 300 # 5 minutes
if should_backup:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_file = os.path.join(BACKUP_DIR, f'scripts_{timestamp}.json')
with open(DATA_FILE, 'r', encoding='utf-8') as f:
backup_data = f.read()
with open(backup_file, 'w', encoding='utf-8') as f:
f.write(backup_data)
# Keep only last 10 backups
backups = sorted([f for f in os.listdir(BACKUP_DIR) if f.startswith('scripts_')])
if len(backups) > 10:
for old_backup in backups[:-10]:
os.remove(os.path.join(BACKUP_DIR, old_backup))
# Save new data
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# ============================================================================
# VERSION CONTROL FUNCTIONS
# ============================================================================
def get_script_base_dir(file_path):
"""Get base directory for script versions - uses archive/ subdirectory
IMPORTANT: This function normalizes ANY path back to the correct project archive folder.
It handles:
- Clean paths: scripts/indicators/my-indicator/my-indicator.pine
- Already archived: scripts/indicators/my-indicator/archive/my-indicator_v1.0.0.pine
- Deeply nested (BUG): scripts/indicators/my-indicator/archive/v1.0/archive/v1.1/v1.2.pine
All return: scripts/indicators/my-indicator/archive
"""
path = Path(file_path)
parts = list(path.parts)
# Extract project name from filename or path
project_name = get_project_name_from_path(file_path)
# Find the project root by looking for the project name in the path
# OR finding the first 'archive' folder and going one level up
project_root_idx = None
# Strategy 1: If 'archive' exists in path, project root is the folder before first 'archive'
if 'archive' in parts:
first_archive_idx = parts.index('archive')
if first_archive_idx > 0:
project_root_idx = first_archive_idx - 1
# Strategy 2: Find folder matching project name
if project_root_idx is None:
for i, part in enumerate(parts):
if part == project_name:
project_root_idx = i
break
# Strategy 3: If file is in flat structure (e.g., scripts/strategies/my-strategy.pine)
if project_root_idx is None:
# Parent directory is the category (strategies, indicators, etc.)
# We need to create project folder
project_root = path.parent / project_name
else:
# Reconstruct path up to project root
project_root = Path(*parts[:project_root_idx + 1])
# Return the archive subdirectory
archive_dir = project_root / 'archive'
return archive_dir
def get_project_name_from_path(file_path):
"""Extract the project name from a file path for version naming"""
# e.g., scripts/strategies/my-strategy/my-strategy.pine -> "my-strategy"
# or scripts/strategies/my-strategy/archive/my-strategy_v1.0.0.pine -> "my-strategy"
path = Path(file_path)
# If in archive folder, parent.parent is project folder
if 'archive' in path.parts:
# Find the project folder (before 'archive')
parts = list(path.parts)
archive_idx = parts.index('archive')
if archive_idx > 0:
return parts[archive_idx - 1]
# If filename matches pattern: name.pine or name_vX.X.X.pine
stem = path.stem
if '_v' in stem:
# Remove version suffix: "my-strategy_v1.0.0" -> "my-strategy"
return stem.split('_v')[0]
# Check if parent folder name matches stem (project structure)
if path.parent.name == stem:
return stem
# Otherwise use the stem directly
return stem
def ensure_version_directory(script):
"""Ensure version directory exists and migrate if needed"""
file_path = script.get('filePath')
if not file_path:
return None
version_dir = get_script_base_dir(file_path)
version_dir.mkdir(parents=True, exist_ok=True)
return version_dir
def migrate_script_to_versioning(script):
"""
Migrate an existing script to version control system
Creates v1.0.0 from current file
"""
file_path = script.get('filePath')
if not file_path or not os.path.exists(file_path):
return False
# Check if already migrated
if 'versions' in script and len(script.get('versions', [])) > 0:
return True # Already versioned
# Read current file
with open(file_path, 'r', encoding='utf-8') as f:
current_code = f.read()
# Create version directory
version_dir = ensure_version_directory(script)
if not version_dir:
return False
# Determine initial version
initial_version = script.get('version', script.get('currentVersion', '1.0.0'))
# Create versioned file with proper naming: project-name_vX.X.X.pine
project_name = get_project_name_from_path(file_path)
version_file = version_dir / f"{project_name}_v{initial_version}.pine"
with open(version_file, 'w', encoding='utf-8') as f:
f.write(current_code)
# Initialize versions array
script['versions'] = [{
'version': initial_version,
'filePath': str(version_file),
'dateCreated': script.get('dateModified', script.get('dateCreated', datetime.utcnow().isoformat() + 'Z')),
'changelog': 'Initial version (auto-migrated)',
'author': script.get('author', 'system'),
'isActive': True
}]
script['currentVersion'] = initial_version
script['version'] = initial_version # Keep top-level version in sync
# Keep old filePath for backward compatibility, but point to version
script['filePath'] = str(version_file)
return True
def create_new_version(script, new_version, code, changelog, author='user'):
"""
Create a new version of a script
Returns: (success, new_version_info, error_message)
"""
try:
# Ensure versioning is set up
if 'versions' not in script or len(script.get('versions', [])) == 0:
migrate_script_to_versioning(script)
# Create version directory
version_dir = ensure_version_directory(script)
if not version_dir:
return False, None, "Could not create version directory"
# Get metadata for header injection
project_name = get_project_name_from_path(script.get('filePath'))
version_file = version_dir / f"{project_name}_v{new_version}.pine"
# Update/inject version metadata in code header
code = update_version_in_code(
code,
new_version,
script_name=script.get('name', 'Unknown Script'),
script_type=script.get('type', 'indicator').upper(),
filename=f"{project_name}_v{new_version}.pine",
changelog=changelog,
author=script.get('author', 'Your Name')
)
# Create new version file with proper naming: project-name_vX.X.X.pine
with open(version_file, 'w', encoding='utf-8') as f:
f.write(code)
# Deactivate all versions
for v in script.get('versions', []):
v['isActive'] = False
# Create new version entry
new_version_info = {
'version': new_version,
'filePath': str(version_file),
'dateCreated': datetime.utcnow().isoformat() + 'Z',
'changelog': changelog,
'author': author,
'isActive': True
}
# Add to versions array
if 'versions' not in script:
script['versions'] = []
script['versions'].append(new_version_info)
# Update current version
script['currentVersion'] = new_version
script['version'] = new_version # Keep top-level version in sync
script['filePath'] = str(version_file)
script['dateModified'] = new_version_info['dateCreated']
return True, new_version_info, None
except Exception as e:
return False, None, str(e)
def get_version_code(script, version):
"""Get code for a specific version"""
versions = script.get('versions', [])
version_info = next((v for v in versions if v['version'] == version), None)
if not version_info:
return None, "Version not found"
file_path = version_info.get('filePath')
if not file_path or not os.path.exists(file_path):
return None, "Version file not found"
try:
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
return code, None
except Exception as e:
return None, str(e)
# Serve static files
@app.route('/')
def index():
return send_from_directory('web', 'index.html')
@app.route('/<path:path>')
def serve_static(path):
if path.startswith('web/'):
return send_from_directory('.', path)
elif path.startswith('data/'):
return send_from_directory('.', path)
return send_from_directory('web', path)
# API Routes
@app.route('/api/scripts', methods=['GET'])
def get_scripts():
"""Get all scripts"""
data = load_scripts()
return jsonify(data)
@app.route('/api/scripts/<script_id>', methods=['GET'])
def get_script(script_id):
"""Get a single script by ID"""
data = load_scripts()
script = next((s for s in data['scripts'] if s['id'] == script_id), None)
if script:
return jsonify(script)
else:
return jsonify({"error": "Script not found"}), 404
@app.route('/api/scripts', methods=['POST'])
def create_script():
"""Create a new script with initial file and version control"""
try:
new_script = request.json
# Validate required fields
required_fields = ['name', 'type', 'filePath']
for field in required_fields:
if field not in new_script:
return jsonify({"error": f"Missing required field: {field}"}), 400
# Generate ID if not provided
if 'id' not in new_script or not new_script['id']:
new_script['id'] = str(uuid.uuid4())[:8]
# Set version if not provided
if 'version' not in new_script:
new_script['version'] = '1.0.0'
initial_version = new_script['version']
# Add timestamps
now = datetime.utcnow().isoformat() + 'Z'
if 'dateCreated' not in new_script:
new_script['dateCreated'] = now
new_script['dateModified'] = now
# Set defaults
if 'pineVersion' not in new_script:
new_script['pineVersion'] = 5
if 'status' not in new_script:
new_script['status'] = 'active'
# Create initial Pine Script file content
script_type = new_script['type']
script_name = new_script['name']
author = new_script.get('author', 'user')
description = new_script.get('description', '')
initial_code = generate_initial_script_code(
script_name,
script_type,
initial_version,
author,
description
)
# Set up version control structure
file_path = new_script['filePath']
version_dir = get_script_base_dir(file_path)
version_dir.mkdir(parents=True, exist_ok=True)
# Create initial version file with proper naming: project-name_vX.X.X.pine
project_name = get_project_name_from_path(file_path)
version_file = version_dir / f"{project_name}_v{initial_version}.pine"
with open(version_file, 'w', encoding='utf-8') as f:
f.write(initial_code)
# Initialize version control
new_script['currentVersion'] = initial_version
new_script['version'] = initial_version # Keep top-level version in sync
new_script['filePath'] = str(version_file)
new_script['versions'] = [{
'version': initial_version,
'filePath': str(version_file),
'dateCreated': now,
'changelog': 'Initial version',
'author': author,
'isActive': True
}]
# Load existing data
data = load_scripts()
# Check for duplicate ID
if any(s['id'] == new_script['id'] for s in data['scripts']):
return jsonify({"error": "Script with this ID already exists"}), 409
# Add new script
data['scripts'].append(new_script)
# Save
save_scripts(data)
return jsonify(new_script), 201
except Exception as e:
return jsonify({"error": str(e)}), 500
def generate_initial_script_code(name, script_type, version, author, description):
"""Generate initial Pine Script code template"""
# Determine declaration based on type
if script_type == 'strategy':
declaration = f'strategy("{name}", overlay=true)'
else: # indicator or study
declaration = f'indicator("{name}", overlay=true)'
template = f"""// This Pine Script was created via Pine Script Library
// © {author}
//@version=5
{declaration}
// ————— Constants
// Add your constants here
// ————— Inputs
// Add your input parameters here
// ————— Calculations
// Add your calculations here
// ————— Visuals
// Add your plots and visual elements here
"""
if description:
# Add description as comment at the top
desc_lines = description.split('\n')
desc_comment = '\n'.join([f'// {line}' for line in desc_lines])
template = f"""// {name}
{desc_comment}
""" + template
return template
@app.route('/api/scripts/<script_id>', methods=['PUT'])
def update_script(script_id):
"""Update an existing script"""
try:
updated_data = request.json
# Load existing data
data = load_scripts()
# Find script
script_index = next((i for i, s in enumerate(data['scripts']) if s['id'] == script_id), None)
if script_index is None:
return jsonify({"error": "Script not found"}), 404
existing_script = data['scripts'][script_index]
# Update timestamp
updated_data['dateModified'] = datetime.utcnow().isoformat() + 'Z'
# Preserve dateCreated if not provided
if 'dateCreated' not in updated_data:
updated_data['dateCreated'] = existing_script.get('dateCreated', updated_data['dateModified'])
# Ensure ID remains the same
updated_data['id'] = script_id
# CRITICAL: Preserve file path and version structure (files on disk don't move when name changes)
if 'filePath' in existing_script:
updated_data['filePath'] = existing_script['filePath']
if 'versions' in existing_script:
updated_data['versions'] = existing_script['versions']
if 'currentVersion' in existing_script:
updated_data['currentVersion'] = existing_script['currentVersion']
# Update script
data['scripts'][script_index] = updated_data
# Save
save_scripts(data)
return jsonify(updated_data)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/scripts/<script_id>', methods=['DELETE'])
def delete_script(script_id):
"""Delete a script"""
try:
# Load existing data
data = load_scripts()
# Find script
script_index = next((i for i, s in enumerate(data['scripts']) if s['id'] == script_id), None)
if script_index is None:
return jsonify({"error": "Script not found"}), 404
# Remove script
deleted_script = data['scripts'].pop(script_index)
# Save
save_scripts(data)
return jsonify({"message": "Script deleted successfully", "script": deleted_script})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/backups', methods=['GET'])
def list_backups():
"""List all available backups"""
try:
backups = sorted([f for f in os.listdir(BACKUP_DIR) if f.startswith('scripts_')], reverse=True)
return jsonify({"backups": backups})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/backups/<filename>', methods=['POST'])
def restore_backup(filename):
"""Restore from a backup file"""
try:
backup_path = os.path.join(BACKUP_DIR, filename)
if not os.path.exists(backup_path):
return jsonify({"error": "Backup file not found"}), 404
# Read backup
with open(backup_path, 'r', encoding='utf-8') as f:
backup_data = json.load(f)
# Save current as backup before restoring
save_scripts(backup_data)
return jsonify({"message": "Backup restored successfully"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/scripts/<script_id>/code', methods=['GET'])
def get_script_code(script_id):
"""Get Pine Script source code for a script (current version or specific version)"""
try:
# Load scripts metadata
data = load_scripts()
script = next((s for s in data['scripts'] if s['id'] == script_id), None)
if not script:
return jsonify({"error": "Script not found"}), 404
# Check if specific version requested
version = request.args.get('version')
if version:
# Get specific version
code, error = get_version_code(script, version)
if error:
return jsonify({"error": error}), 404
versions = script.get('versions', [])
version_info = next((v for v in versions if v['version'] == version), None)
return jsonify({
"id": script_id,
"name": script.get('name'),
"version": version,
"filePath": version_info.get('filePath') if version_info else None,
"code": code,
"versionInfo": version_info
})
else:
# Get current version - PRIORITIZE versioned file if it exists
current_version = script.get('currentVersion')
if current_version and 'versions' in script and len(script.get('versions', [])) > 0:
# Use the versioned file (from version system)
code, error = get_version_code(script, current_version)
if not error:
versions = script.get('versions', [])
version_info = next((v for v in versions if v['version'] == current_version), None)
return jsonify({
"id": script_id,
"name": script.get('name'),
"version": current_version,
"filePath": version_info.get('filePath') if version_info else None,
"code": code,
"versionInfo": version_info
})
else:
# Fall back to main file if versioned file not found
file_path = script.get('filePath')
if not file_path or not os.path.exists(file_path):
return jsonify({"error": "Script file not found"}), 404
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
return jsonify({
"id": script_id,
"name": script.get('name'),
"version": current_version,
"filePath": file_path,
"code": code
})
else:
# No version system yet - use main file
file_path = script.get('filePath')
if not file_path:
return jsonify({"error": "No file path specified for this script"}), 400
# Read the Pine Script file
if not os.path.exists(file_path):
return jsonify({"error": f"Script file not found at: {file_path}"}), 404
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
return jsonify({
"id": script_id,
"name": script.get('name'),
"version": script.get('currentVersion'),
"filePath": file_path,
"code": code
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/scripts/<script_id>/versions', methods=['GET'])
def get_script_versions(script_id):
"""Get version history for a script"""
try:
# Load scripts metadata
data = load_scripts()
script = next((s for s in data['scripts'] if s['id'] == script_id), None)
if not script:
return jsonify({"error": "Script not found"}), 404
# Auto-migrate if needed
if 'versions' not in script or len(script.get('versions', [])) == 0:
migrate_script_to_versioning(script)
# Save migration
script_index = next((i for i, s in enumerate(data['scripts']) if s['id'] == script_id), None)
if script_index is not None:
data['scripts'][script_index] = script
save_scripts(data)
versions = script.get('versions', [])
# Sort by date (newest first)
sorted_versions = sorted(versions, key=lambda v: v.get('dateCreated', ''), reverse=True)
return jsonify({
'scriptId': script_id,
'currentVersion': script.get('currentVersion'),
'versions': sorted_versions,
'totalVersions': len(sorted_versions)
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/scripts/<script_id>/versions/<version>/restore', methods=['POST'])
def restore_version(script_id, version):
"""
Restore a previous version
Options:
- mode: 'activate' (make this version current) or 'new' (create new version based on this)
"""
try:
request_data = request.json or {}
mode = request_data.get('mode', 'activate') # Default: activate
# Load scripts metadata
data = load_scripts()
script = next((s for s in data['scripts'] if s['id'] == script_id), None)
if not script:
return jsonify({"error": "Script not found"}), 404
# Get the version code
code, error = get_version_code(script, version)
if error:
return jsonify({"error": error}), 404
if mode == 'activate':
# Set this version as active
versions = script.get('versions', [])
# Deactivate all
for v in versions:
v['isActive'] = False
# Activate requested version
version_info = next((v for v in versions if v['version'] == version), None)
if version_info:
version_info['isActive'] = True
script['currentVersion'] = version
script['version'] = version # Keep top-level version in sync
script['filePath'] = version_info['filePath']
script['dateModified'] = datetime.utcnow().isoformat() + 'Z'
result = {
'success': True,
'mode': 'activate',
'activeVersion': version,
'message': f'Version {version} is now active'
}
elif mode == 'new':
# Create new version based on this one
current_version = script.get('currentVersion', '1.0.0')
new_version = increment_version(current_version)
changelog = f'Created from version {version}'
success, version_info, error = create_new_version(
script,
new_version,
code,
changelog,
author=request_data.get('author', 'user')
)
if not success:
return jsonify({"error": error or "Failed to create new version"}), 500
result = {
'success': True,
'mode': 'new',
'newVersion': new_version,
'basedOn': version,
'message': f'Created new version {new_version} based on {version}',
'versionInfo': version_info
}
else:
return jsonify({"error": "Invalid mode. Use 'activate' or 'new'"}), 400
# Save changes
script_index = next((i for i, s in enumerate(data['scripts']) if s['id'] == script_id), None)
if script_index is not None:
data['scripts'][script_index] = script
save_scripts(data)
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/scripts/<script_id>/review', methods=['GET'])
def review_script_code(script_id):
"""Review Pine Script code against standards and best practices (current or specific version)"""
try:
# Load scripts metadata
data = load_scripts()
script = next((s for s in data['scripts'] if s['id'] == script_id), None)
if not script:
return jsonify({"error": "Script not found"}), 404
# Check if specific version requested
version = request.args.get('version')
if version:
# Get specific version code
code, error = get_version_code(script, version)
if error:
return jsonify({"error": error}), 404
script_name = f"{script.get('name', 'Unknown')} (v{version})"
else:
# Get current version - PRIORITIZE versioned file if it exists
current_version = script.get('currentVersion')
if current_version and 'versions' in script and len(script.get('versions', [])) > 0:
# Use the versioned file (from version system)
code, error = get_version_code(script, current_version)
if not error:
script_name = f"{script.get('name', 'Unknown')} (v{current_version})"
else:
# Fall back to main file if versioned file not found
file_path = script.get('filePath')
if not file_path or not os.path.exists(file_path):
return jsonify({"error": "Script file not found"}), 404
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
script_name = f"{script.get('name', 'Unknown')} (main file)"
else:
# No version system yet - use main file
file_path = script.get('filePath')
if not file_path:
return jsonify({"error": "No file path specified for this script"}), 400
# Read the Pine Script file
if not os.path.exists(file_path):
return jsonify({"error": f"Script file not found at: {file_path}"}), 404
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
script_name = f"{script.get('name', 'Unknown')} (main file)"
# Perform code review
review_results = perform_code_review(code, script_name)
# Add version info to results
review_results['reviewedVersion'] = version if version else script.get('currentVersion')
return jsonify(review_results)
except Exception as e:
return jsonify({"error": str(e)}), 500
def perform_code_review(code, script_name):
"""
Comprehensive code review based on:
- PINE_SCRIPT_STANDARDS.md
- LOGICAL_SANITY_CHECKS.md
- SANITY_CHECKS_QUICK_REF.md
"""
issues = []
recommendations = []
lines = code.split('\n')
# ============================================================================
# 1. VERSION CHECK (CRITICAL)
# ============================================================================
# Check for version 5 or 6 (both are acceptable)
has_version_5 = '//@version=5' in code
has_version_6 = '//@version=6' in code
if not has_version_5 and not has_version_6:
issues.append({
'category': 'Script Structure',
'check': 'Pine Script Version',
'severity': 'CRITICAL',
'message': 'Script must use //@version=5 or //@version=6 declaration',
'line': 1
})
elif has_version_5:
issues.append({
'category': 'Script Structure',
'check': 'Pine Script Version',
'severity': 'PASS',
'message': 'Using Pine Script v5 ✓'
})
else: # has_version_6
issues.append({
'category': 'Script Structure',
'check': 'Pine Script Version',
'severity': 'PASS',
'message': 'Using Pine Script v6 ✓'
})
# ============================================================================
# 2. NAMING CONVENTIONS CHECK
# ============================================================================
# Track multi-line comment blocks
in_multiline_comment = False
# Check for snake_case variables (should be camelCase)
# Pattern: snake_case followed by = (but not ==, !=, <=, >=)
# This should match variable assignments like: my_var = value
snake_case_pattern = re.compile(r'\b([a-z]+_[a-z_]+)\s*=(?!=|<|>)')
for i, line in enumerate(lines, 1):
stripped = line.strip()
# Track multi-line comment state
if '/*' in line:
in_multiline_comment = True
if '*/' in line:
in_multiline_comment = False
continue
# Skip comments
if '=' in line and not stripped.startswith('//') and not in_multiline_comment:
matches = snake_case_pattern.findall(line)
for match in matches:
# Skip if it's a constant (all caps)
if match.isupper():
continue
# Skip function parameters (they appear after opening paren or comma within parens)
# Check if this is inside a function call by looking for context
# Pattern: word_name = appears after ( or , and before ) - this is a function parameter
if re.search(r'[(,]\s*[^)]*\b' + re.escape(match) + r'\s*=', line):
continue # This is a function parameter like strategy(..., initial_capital=50000)
# This is a real variable assignment
issues.append({
'category': 'Naming Conventions',
'check': 'camelCase Variables',
'severity': 'HIGH',
'message': f'Variable "{match}" uses snake_case. Should use camelCase (e.g., "{to_camel_case(match)}")',
'line': i,
'code': line.strip()
})
# Reset comment tracking
in_multiline_comment = False
# Check for constants without SNAKE_CASE
const_pattern = re.compile(r'(?:const|^)\s+(?:int|float|bool|string|color)\s+([a-z][a-zA-Z0-9]*)\s*=')
for i, line in enumerate(lines, 1):
stripped = line.strip()
# Track multi-line comment state
if '/*' in line:
in_multiline_comment = True
if '*/' in line:
in_multiline_comment = False
continue
# Skip comments
if ('const' in line or (stripped and not stripped.startswith('//'))) and not in_multiline_comment:
matches = const_pattern.findall(line)
for match in matches:
if match.islower() and 'input' not in match.lower():
issues.append({
'category': 'Naming Conventions',
'check': 'SNAKE_CASE Constants',
'severity': 'HIGH',
'message': f'Constant "{match}" should use SNAKE_CASE (e.g., "{match.upper()}")',
'line': i,
'code': line.strip()
})
# Reset comment tracking
in_multiline_comment = False
# Check for input variables without Input suffix
input_pattern = re.compile(r'(\w+)\s*=\s*input\.(bool|int|float|string|color|time|timeframe|source|session)')
for i, line in enumerate(lines, 1):
stripped = line.strip()
# Track multi-line comment state
if '/*' in line:
in_multiline_comment = True
if '*/' in line:
in_multiline_comment = False
continue
# Skip comments
if not stripped.startswith('//') and not in_multiline_comment:
matches = input_pattern.findall(line)
for var_name, input_type in matches:
# Check if variable name ends with Input suffix
if not var_name.endswith('Input'):
suggested_name = var_name + 'Input'
issues.append({
'category': 'Naming Conventions',
'check': 'Input Suffix',
'severity': 'HIGH',
'message': f'Input variable "{var_name}" should have "Input" suffix (e.g., "{suggested_name}")',
'line': i,