-
Notifications
You must be signed in to change notification settings - Fork 2
/
lab.coffee
946 lines (678 loc) · 25 KB
/
lab.coffee
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
fs = require 'fs'
progress_bar = require('progress')
mathjs = require 'mathjs'
require './shared'
history = require './trade_history'
exchange = require './exchange'
global.pusher = require './pusher'
crunch = require './crunch'
global.position_status = {}
#########################
# Main event loop
simulate = (ts, callback) ->
ts = Math.floor(ts)
time = from_cache('time')
extend time,
earliest: ts - config.length
latest: ts
save time
global.tick = tick =
time: 0
global.t_ =
qtick: 0
hustle: 0
exec: 0
feature_tick: 0
eval_pos: 0
check_new: 0
check_exit: 0
check_unfilled: 0
balance: 0
pos_status: 0
# gc: 0
# x: 0
# y: 0
# z: 0
# a: 0
# b: 0
# c: 0
price_data = fetch('price_data')
start = ts - config.length - history.longest_requested_history
tick.time = ts - config.length
tick.start = start
history.advance tick.time
start_idx = history.trade_idx
balance = from_cache('balances')
extend balance,
updated: 0
balances:
c1: 0
c2: 0
deposits:
c1: 0
c2: 0
accounted_for:
c1: 0
c2: 0
on_order:
c1: 0
c2: 0
exchange.get_my_exchange_fee {}, (fees) ->
balance.maker_fee = fees.maker_fee
balance.taker_fee = fees.taker_fee
dealers = get_dealers()
$c2 = price_data.c2?[0].close or price_data.c1xc2[0].close
$c1 = price_data.c1?[0].close or 1
for dealer in dealers
settings = from_cache(dealer).settings
budget = settings.$budget or 100
if config.deposit_allocation == '50/50'
c1_budget = budget * (1 - (settings.ratio or .5) ) / $c1
c2_budget = budget * (settings.ratio or .5) / $c2
else if config.deposit_allocation == 'c1'
c1_budget = budget * .98 / $c1
c2_budget = budget * .02 / $c2
else if config.deposit_allocation == 'c2'
c1_budget = budget * .02 / $c1
c2_budget = budget * .98 / $c2
balance[dealer] =
balances:
c2: c2_budget
c1: c1_budget
deposits:
c2: c2_budget
c1: c1_budget
accounted_for:
c1: 0
c2: 0
on_order:
c1: 0
c2: 0
balance.balances.c2 += balance[dealer].balances.c2
balance.balances.c1 += balance[dealer].balances.c1
balance.deposits.c2 += balance[dealer].deposits.c2
balance.deposits.c1 += balance[dealer].deposits.c1
save balance
balance = bus.fetch 'balances'
t = ':perperper% :perbytrade% :etas :elapsed :ticks'
for k,v of t_
t += " #{k}-:#{k}"
bar = new progress_bar t,
complete: '='
incomplete: ' '
width: 40
renderThrottle: 500
total: Math.ceil (time.latest - time.earliest) / (.0 * pusher.tick_interval_no_unfilled + 1.0 * pusher.tick_interval)
ticks = 0
started_at = Date.now()
price_idx = 0
end = ->
history.trades = [] # free memory
if global.gc
global.gc()
else
console.log('Garbage collection unavailable. Pass --expose-gc.');
if config.produce_heapdump
try
heapdump = require('heapdump')
heapdump.writeSnapshot()
catch e
console.log 'Could not take snapshot'
log_results()
console.time('saving db')
global.timerrrr = Date.now()
save balance
for name in (get_all_actors() or [])
d = from_cache name
save d
console.timeEnd('saving db')
if config.log_level > 1
console.log "\nDone simulating! That took #{(Date.now() - started_at) / 1000} seconds"
console.log config if config.persist
console.log "PORT: #{bus.port}"
callback?()
one_tick = ->
t = Date.now()
has_unfilled = false
for dealer,positions of open_positions when positions.length > 0
for pos in positions
if (pos.entry && !pos.entry.closed) || (pos.exit && !pos.exit.closed)
has_unfilled = true
break
break if has_unfilled
inc = if has_unfilled
pusher.tick_interval
else
pusher.tick_interval_no_unfilled
tick.time += inc
start += inc
history.advance(tick.time)
simulation_done = tick.time > ts - pusher.tick_interval * 10
######################
#### Accounting
dealers_with_open = (dealer for dealer,positions of open_positions when positions.length > 0)
if dealers_with_open.length > 0
# check if any positions have subsequently closed
yyy = Date.now()
update_position_status balance, dealers_with_open
t_.pos_status += Date.now() - yyy
yyy = Date.now()
update_balance balance, dealers_with_open
t_.balance += Date.now() - yyy
#####################
if !simulation_done
######################
#### Main call. Where the action is.
#pusher.hustle balance, trades
pusher.hustle balance
######################
if simulation_done
return end()
####################
#### Efficiency measures
# xxxx = Date.now()
if ticks % 50000 == 1
global.gc?()
if ticks % 100 == 99
purge_position_status()
# t_.gc += Date.now() - xxxx
####################
#####################
#### Progress bar
if config.log_level > 0
t_sec = {}
for k,v of t_
t_sec[k] = Math.round(v/1000)
perperper = Math.round(100 * (tick.time - time.earliest) / (time.latest - time.earliest))
perbytrade = Math.round(100 * (start_idx - history.trade_idx) / start_idx )
bar.tick 1, extend {ticks,perperper,perbytrade}, t_sec
#####################
ticks++
t_.qtick += Date.now() - t
setImmediate one_tick
setImmediate one_tick
update_balance = (balance, dealers_with_open) ->
btc = eth = btc_on_order = eth_on_order = 0
for dealer in dealers_with_open
positions = open_positions[dealer]
dbtc = deth = dbtc_on_order = deth_on_order = 0
for pos in positions
if pos.entry.type == 'buy'
buy = pos.entry
sell = pos.exit
else
buy = pos.exit
sell = pos.entry
if buy
# used or reserved for buying trade.amount eth
for_purchase = if buy.flags?.market then buy.to_fill else buy.to_fill * buy.rate
dbtc_on_order += for_purchase
dbtc -= for_purchase
if buy.fills?.length > 0
for fill in buy.fills
deth += fill.amount
dbtc -= fill.total
if config.exchange == 'poloniex'
deth -= fill.fee
else
dbtc -= fill.fee
if sell
for_sale = sell.to_fill
deth_on_order += for_sale
deth -= for_sale
if sell.fills?.length > 0
for fill in sell.fills
deth -= fill.amount
dbtc += fill.total
dbtc -= fill.fee
btc += dbtc
eth += deth
btc_on_order += dbtc_on_order
eth_on_order += deth_on_order
dbalance = balance[dealer]
dbalance.balances.c1 = dbalance.deposits.c1 + dbtc + dbalance.accounted_for.c1
dbalance.balances.c2 = dbalance.deposits.c2 + deth + dbalance.accounted_for.c2
dbalance.on_order.c1 = dbtc_on_order
dbalance.on_order.c2 = deth_on_order
if config.enforce_balance && (dbalance.balances.c1 < 0 || dbalance.balances.c2 < 0)
msg =
message: 'negative balance!?!'
balance: balance.balances
dbalance: balance[dealer]
dealer: dealer
config: config
console.log ''
fills = []
fills_out = []
pos = null
for pos in from_cache(dealer).positions
for trade in [pos.entry, pos.exit] when trade
fills = fills.concat trade.fills
console.log trade if config.log_level > 1
for fill in trade.fills
if fill.type == 'sell'
fills_out.push "#{pos.key or 'none'}\t#{trade.entry or false}\t#{trade.created}\t#{fill.order_id or '000'}\t#{fill.total}\t-#{fill.amount}\t#{fill.fee}"
else
fills_out.push "#{pos.key or 'none'}\t#{trade.entry or false}\t#{trade.created}\t#{fill.order_id or '000'}\t-#{fill.total}\t#{fill.amount}\t#{fill.fee}"
# for pos in from_cache(dealer).positions
# for t in [pos.entry, pos.exit] when t
# # msg["#{pos.created}-#{t.type}"] = t
# amt = 0
# tot = 0
# for f,idx in (t.fills or [])
# # msg["#{pos.created}-#{t.type}-f#{idx}"] = f
# amt += f.amount
# tot += f.total
# # console.log
# # type: t.type
# # amt: amt
# # tot: tot
# # fills: (t.fills or []).length
# # closed: t.closed
# console.log t
console.log fills_out
console.assert false, msg
balance.balances.c1 = balance.deposits.c1 + btc + balance.accounted_for.c1
balance.balances.c2 = balance.deposits.c2 + eth + balance.accounted_for.c2
balance.on_order.c1 = btc_on_order
balance.on_order.c2 = eth_on_order
global.trades_closed = {}
purge_position_status = ->
new_position_status = {}
for name, open of open_positions when open.length > 0
for pos in open
for trade in [pos.entry, pos.exit] when trade && !trade.closed
```
key = `${pos.dealer}-${trade.created}-${trade.type}-${trade.rate}`
```
new_position_status[key] = global.position_status[key]
for k,v of global.position_status
if k not of new_position_status
delete global.position_status[k]
update_position_status = (balance, dealers_with_open) ->
end_idx = history.trade_idx
for dealer in dealers_with_open
maker_fee = from_cache('balances').maker_fee
taker_fee = from_cache('balances').taker_fee
open = open_positions[dealer]
closed = []
for pos in open
for trade in [pos.entry, pos.exit] when trade && !trade.closed
```
key = `${pos.dealer}-${trade.created}-${trade.type}-${trade.rate}`
```
status = global.position_status[key]
if trade.to_fill > 0 && (!status? || end_idx < status.idx + 100 )
status = global.position_status[key] = fill_order trade, status
# console.log '\nFILLLLLLLL\n', key, end_idx, status?.idx, status?.fills?.length
if status?.fills?.length > 0
filled = 0
for fill in (status.fills or [])
if fill.date > tick.time
break
amt = fill.amount
rate = fill.rate
if trade.flags?.market && trade.type == 'buy'
to_fill = trade.to_fill
done = amt * rate >= to_fill
fill.total = if !done then amt * rate else to_fill
fill.amount = if !done then amt else to_fill / rate
fill.fee = if trade.type == 'buy' && config.exchange == 'poloniex'
fill.amount * maker_fee
else
fill.amount * fill.rate * maker_fee
trade.to_fill -= fill.total
else
to_fill = trade.to_fill
done = fill.amount >= to_fill || trade.flags?.market
if done
fill.amount = to_fill
xfee = if fill.is_maker then maker_fee else taker_fee
fill.fee = if trade.type == 'buy' && config.exchange == 'poloniex'
fill.amount * xfee
else
fill.amount * fill.rate * xfee
fill.total = fill.amount * rate
trade.to_fill -= fill.amount
fill.type = trade.type
trade.fills.push fill
filled += 1
if filled > 0
status.fills = status.fills.slice(filled)
# if trade.to_fill < 0
# console.assert false,
# message: 'Overfilled!'
# trade: trade
# fills: trade.fills
if trade.to_fill == 0
trade.closed = trade.fills[trade.fills.length - 1].date
global.position_status[key] = undefined
if (pos.entry?.closed && pos.exit?.closed) || (dealers[dealer].never_exits && pos.entry?.closed)
pos.closed = Math.max pos.entry.closed, (pos.exit?.closed or 0)
closed.push pos
for pos in closed
idx = open.indexOf(pos)
open.splice idx, 1
name = pos.dealer
cur_c1 = balance.accounted_for.c1
cur_c2 = balance.accounted_for.c2
for trade in [pos.entry, pos.exit] when trade
close_trade pos, trade
if trade.type == 'buy'
balance.accounted_for.c2 += trade.amount
balance.accounted_for.c1 -= trade.total
balance[name].accounted_for.c2 += trade.amount
balance[name].accounted_for.c1 -= trade.total
else
balance.accounted_for.c2 -= trade.amount
balance.accounted_for.c1 += trade.total
balance[name].accounted_for.c2 -= trade.amount
balance[name].accounted_for.c1 += trade.total
balance.accounted_for.c2 -= trade.c2_fees
balance.accounted_for.c1 -= trade.c1_fees
balance[name].accounted_for.c2 -= trade.c2_fees
balance[name].accounted_for.c1 -= trade.c1_fees
pos.profit = (balance.accounted_for.c1 - cur_c1) / pos.exit.rate + (balance.accounted_for.c2 - cur_c2)
fill_order = (my_trade, status) ->
end_idx = @history.trade_idx
status ||= {
fills: []
idx: false
became_maker: false
}
my_amount = my_trade.amount
my_rate = my_trade.rate
is_sell = my_trade.type == 'sell'
my_created = my_trade.created
order_placement_lag = config.order_placement_lag
is_market = my_trade.flags?.market
if status.idx
start_at = status.idx
else
start_at = end_idx
to_fill = my_trade.to_fill
console.assert to_fill > 0
status.fills ||= []
fills = status.fills
init = false
for idx in [start_at..0] by -1
trade = history.trades[idx]
if !init
if trade.date < my_created + order_placement_lag
continue
else
init = true
if !status.became_maker
status.became_maker = trade.date - (my_created + order_placement_lag) > 1 * 60 || (is_sell && trade.rate <= my_rate) || (!is_sell && trade.rate >= my_rate)
if (!is_sell && trade.rate <= my_rate) || \
( is_sell && trade.rate >= my_rate) || is_market
if is_market
if (is_sell && trade.rate < my_rate) || (!is_sell && trade.rate > my_rate)
rate = trade.rate
else
rate = my_rate
else
rate = my_rate
is_maker = status.became_maker && !is_market
fill =
date: trade.date
rate: rate
amount: trade.amount
maker: is_maker
fills.push fill
if ((!is_market || is_sell) && trade.amount >= to_fill) || \
( (is_market && !is_sell) && trade.total >= to_fill)
status.idx = idx
return status
else
if is_market && !is_sell
to_fill -= fill.amount * fill.rate
else
to_fill -= fill.amount
if !is_market && (!history.trades[end_idx] || trade.date > history.trades[end_idx].date + 30 * 60)
status.idx = idx
return status
store_analysis = ->
balance = from_cache 'balance'
# analysis of positions
fs = require('fs')
if !fs.existsSync 'analyze'
fs.mkdirSync 'analyze'
dir = "analyze/#{config.end - config.length}-#{config.end}"
if !fs.existsSync dir
fs.mkdirSync dir
dealer_names = get_dealers()
sample = null
sample_dealer = null
for name in dealer_names
for pos in (from_cache(name).positions or [])
sample = dealers[name].analyze pos, balance.maker_fee
sample_dealer = name
break
break if sample
return if !sample
cols = Object.keys(sample.dependent).concat(Object.keys(get_settings(sample_dealer))).concat Object.keys(sample.independent)
rows = []
rows.push cols
for name in dealer_names
positions = from_cache(name).positions
dealer = dealers[name]
settings = get_settings(name) or {}
for pos in positions
row = dealer.analyze(pos, balance.maker_fee)
continue if !row
independent = extend {}, row.independent, settings
rows.push ( (if col of independent then independent[col] else row.dependent[col]) for col in cols)
fname = "#{dir}/positions.txt"
fs.writeFileSync fname, (r.join('\t') for r in rows).join('\n'), { flag : 'w' }
# analysis of dealers
KPI (all_stats) ->
cols = ['Name']
pieces = {}
for name in get_dealers()
for part, idx in name.split('&')
if idx > 0
[param,val] = part.split('=')
pieces[param] ||= {}
pieces[param][val] = true
params = (p for p,v of pieces when Object.keys(v).length > 1)
cols = cols.concat params
for measure, __ of dealer_measures(all_stats)
cols.push measure
rows = [cols]
for name in get_dealers()
stats = all_stats[name]
my_params = {}
for part, idx in name.split('&')
if idx > 0
[param,val] = part.split('=')
my_params[param] = val
else
strat = part
row = [strat]
for param in params
if param of my_params
row.push my_params[param]
else
row.push ''
for measure, calc of dealer_measures(all_stats)
row.push calc(name)
rows.push row
fname = "#{dir}/dealers.txt"
fs.writeFileSync fname, (r.join('\t') for r in rows).join('\n'), { flag : 'w' }
log_results = ->
if config.analyze
console.log 'Exporting analysis'
store_analysis()
KPI (all_stats) ->
balances = from_cache 'balances'
row = [config.name, config.c1, config.c2, config.exchange, config.end - config.length, config.end, all_stats.all.$c1_start, all_stats.all.$c2_start, all_stats.all.$c1_end, all_stats.all.$c2_end, balances.deposits.c1, balances.deposits.c2, balances.balances.c1, balances.balances.c2]
for measure, calc of dealer_measures(all_stats)
row.push calc('all')
console.log '\x1b[36m%s\x1b[0m', "#{row[0]} made #{row[18]} profit on #{row[19]} completed trades at #{row[14]} CAGR"
if config.log_results
fs = require('fs')
if !fs.existsSync('logs')
fs.mkdirSync 'logs'
fname = "logs/#{config.log_results}.txt"
if !fs.existsSync(fname)
cols = ['Name', 'Currency1', 'Currency2', 'Exchange', 'Start', 'End', '$c1_start', '$c2_start', '$c1_end', '$c2_end', 'c1_deposit', 'c2_deposit', 'c1_end', 'c2_end']
for measure, __ of dealer_measures(all_stats)
cols.push measure
else
cols = []
rows = [cols]
rows.push row
out = fs.openSync fname, 'a'
fs.writeSync out, (r.join('\t') for r in rows).join('\n')
fs.closeSync out
reset = ->
global.config = {}
KPI.initialized = false
global.open_positions = {}
history.trades = []
pusher.init
history: history
clear_all_positions: true
lab = module.exports =
experiment: (conf, callback) ->
global.config = {}
global.config = defaults global.config, conf,
key: 'config'
exchange: 'poloniex'
simulation: true
eval_entry_every_n_seconds: 60
eval_exit_every_n_seconds: 60
eval_unfilled_every_n_seconds: 60
length: 12 * 24 * 60 * 60
c1: 'BTC'
c2: 'ETH'
accounting_currency: 'USDT'
order_placement_lag: 1
log: true
enforce_balance: true
persist: false
analyze: false
produce_heapdump: false
offline: false
auto_shorten_time: true
deposit_allocation: '50/50'
log_level: 1
save config
# set globals
global.position_status = {}
ts = config.end or now()
# history.load_chart_history "c1xc2", config.c1, config.c2, ts - 20 * 365 * 24 * 60 * 60, ts, ->
# console.log 'use me to get earliest trade for pair', config.c1, config.c2
# process.exit()
# return
pusher.init
history: history
clear_all_positions: true
console.assert !isNaN(history.longest_requested_history),
message: 'Longest requested history is NaN. Perhaps you haven\'t registered any dealers'
# console.log 'longest requested history:', history.longest_requested_history
history_width = history.longest_requested_history + config.length + 24 * 60 * 60
earliest_trade_for_pair = exchange.get_earliest_trade {only_high_volume: config.only_high_volume, exchange: config.exchange, c1: config.c1, c2: config.c2, accounting_currency: config.accounting_currency}
if ts > earliest_trade_for_pair
if config.auto_shorten_time && ts - history_width < earliest_trade_for_pair
shrink_by = earliest_trade_for_pair - (ts - history_width) + 24 * 60 * 60
config.length -= shrink_by
history_width = history.longest_requested_history + config.length + 24 * 60 * 60
console.log "Shortened simulation", {shrink_by, end: ts, start: ts - history_width, history_width, earliest_trade_for_pair}
if ts - history_width >= earliest_trade_for_pair
console.log "Running #{Object.keys(dealers).length} dealers" if config.log_level > 0
history.load_price_data
start: ts - history_width
end: ts
callback: ->
console.log "...loading #{ (history_width / 60 / 60 / 24).toFixed(2) } days of trade history, relative to #{ts}" if config.log_level > 1
history.load ts - history_width, ts, ->
console.log "...experimenting!" if config.log_level > 1
simulate ts, callback
else
console.log "Can't experiment during that time. The currency pair wasn't trading before the start date."
callback()
else
console.log "Can't experiment during that time. The currency pair wasn't trading before the end date."
callback()
setup: ({persist, port, db_name, clear_old, no_client}) ->
global.pointerify = true
global.upload_dir = 'static/'
global.bus = require('statebus').serve
port: port
file_store: false
client: false
bus.honk = false
if persist
if clear_old && fs.existsSync(db_name)
fs.unlinkSync(db_name)
bus.sqlite_store
filename: db_name
use_transactions: true
backups: false
global.save = bus.save
global.fetch = (key) ->
bus.fetch deslash key
global.del = bus.del
if !no_client
require 'coffee-script'
require './shared'
express = require('express')
bus.http.use('/node_modules', express.static('node_modules'))
bus.http.use('/node_modules', express.static('meth/node_modules'))
bus.http.use('/meth/vendor', express.static('meth/vendor'))
# taken from statebus server.js. Just wanted different client path.
bus.http_serve '/meth/:filename', (filename) ->
filename = deslash filename
source = bus.read_file(filename)
if filename.match(/\.coffee$/)
try
compiled = require('coffee-script').compile source,
filename: filename
bare: true
sourceMap: true
catch e
console.error('Could not compile ' + filename + ': ', e)
return ''
compiled = require('coffee-script').compile(source, {filename: filename, bare: true, sourceMap: true})
source_map = JSON.parse(compiled.v3SourceMap)
source_map.sourcesContent = source
compiled = 'window.dom = window.dom || {}\n' + compiled.js
compiled = 'window.ui = window.ui || {}\n' + compiled
btoa = (s) -> return new Buffer(s.toString(),'binary').toString('base64')
# Base64 encode it
compiled += '\n'
compiled += '//# sourceMappingURL=data:application/json;base64,'
compiled += btoa(JSON.stringify(source_map)) + '\n'
compiled += '//# sourceURL=' + filename
return compiled
else return source
bus.http.get '/*', (r,res) =>
paths = r.url.split('/')
paths.shift() if paths[0] == ''
console.log r.url
prefix = ''
server = "statei://localhost:#{bus.port}"
html = """
<!DOCTYPE html>
<html>
<head>
<script type="coffeedom">
bus.honk = false
#</script>
<script src="#{prefix}/node_modules/statebus/client.js" server="#{server}"></script>
<script src="#{prefix}/meth/vendor/d3.js"></script>
<script src="#{prefix}/meth/vendor/md5.js"></script>
<script src="#{prefix}/meth/vendor/plotly.js"></script>
<script src="#{prefix}/meth/shared.coffee"></script>
<script src="#{prefix}/meth/crunch.coffee"></script>
<script src="#{prefix}/meth/dash.coffee"></script>
<link rel="stylesheet" href="#{prefix}/meth/vendor/fonts/Bebas Neue/bebas.css" type="text/css"/>
</head>
<body>
</body>
</html>
"""
res.send(html)
bus.http.use('/node_modules', express.static('node_modules'))