-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathorders.rs
More file actions
1390 lines (1205 loc) · 44.8 KB
/
orders.rs
File metadata and controls
1390 lines (1205 loc) · 44.8 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
use std::cmp::min;
use std::ops::Sub;
use crate::msg;
use crate::controller::position::PositionDelta;
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm::calculate_amm_available_liquidity;
use crate::math::casting::Cast;
use crate::math::constants::{
BASE_PRECISION_I128, FEE_ADJUSTMENT_MAX, MARGIN_PRECISION_I128, MARGIN_PRECISION_U128,
MAX_PREDICTION_MARKET_PRICE, MAX_PREDICTION_MARKET_PRICE_I64, OPEN_ORDER_MARGIN_REQUIREMENT,
PERCENTAGE_PRECISION_I128, PERCENTAGE_PRECISION_U64, PRICE_PRECISION_I128, PRICE_PRECISION_U64,
QUOTE_PRECISION_I128, SPOT_WEIGHT_PRECISION, SPOT_WEIGHT_PRECISION_I128,
};
use crate::state::protected_maker_mode_config::ProtectedMakerParams;
use crate::state::user::OrderBitFlag;
use crate::{load, math, FeeTier};
use crate::math::margin::{
calculate_margin_requirement_and_total_collateral_and_liability_info, MarginRequirementType,
};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_strict_token_value;
use crate::math::spot_withdraw::get_max_withdraw_for_market_with_token_amount;
use crate::math_error;
use crate::print_error;
use crate::state::margin_calculation::{MarginCalculation, MarginContext};
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::oracle_map::OracleMap;
use crate::state::order_params::PostOnlyParam;
use crate::state::perp_market::{PerpMarket, AMM};
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_market::SpotMarket;
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::user::{
MarketType, Order, OrderFillSimulation, OrderStatus, OrderTriggerCondition, PerpPosition, User,
};
use crate::state::user_map::UserMap;
use crate::validate;
#[cfg(test)]
mod tests;
pub fn calculate_base_asset_amount_for_amm_to_fulfill(
order: &Order,
market: &PerpMarket,
limit_price: Option<u64>,
override_fill_price: Option<u64>,
existing_base_asset_amount: i64,
fee_tier: &FeeTier,
) -> DriftResult<(u64, Option<u64>)> {
let limit_price = if let Some(override_fill_price) = override_fill_price {
if let Some(limit_price) = limit_price {
validate!(
(limit_price >= override_fill_price && order.direction == PositionDirection::Long)
|| (limit_price <= override_fill_price
&& order.direction == PositionDirection::Short),
ErrorCode::InvalidAmmLimitPriceOverride,
"override_limit_price={} not better than order_limit_price={}",
override_fill_price,
limit_price
)?;
}
Some(override_fill_price)
} else {
limit_price
};
if order.must_be_triggered() && !order.triggered() {
return Ok((0, limit_price));
}
let limit_price_with_buffer =
calculate_limit_price_with_buffer(order, limit_price, fee_tier, market.fee_adjustment)?;
let base_asset_amount = calculate_base_asset_amount_to_fill_up_to_limit_price(
order,
market,
limit_price_with_buffer,
Some(existing_base_asset_amount),
)?;
let max_base_asset_amount = calculate_amm_available_liquidity(&market.amm, &order.direction)?;
Ok((min(base_asset_amount, max_base_asset_amount), limit_price))
}
fn calculate_limit_price_with_buffer(
order: &Order,
limit_price: Option<u64>,
fee_tier: &FeeTier,
fee_adjustment: i16,
) -> DriftResult<Option<u64>> {
if !order.post_only {
Ok(limit_price)
} else if let Some(limit_price) = limit_price {
let mut buffer = limit_price
.safe_mul(fee_tier.maker_rebate_numerator.cast()?)?
.safe_div(fee_tier.maker_rebate_denominator.cast()?)?;
if fee_adjustment < 0 {
let buffer_adjustment = buffer
.safe_mul(fee_adjustment.abs().cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?;
buffer = buffer.saturating_sub(buffer_adjustment);
} else if fee_adjustment > 0 {
let buffer_adjustment = buffer
.safe_mul(fee_adjustment.cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?;
buffer = buffer.saturating_add(buffer_adjustment);
}
match order.direction {
PositionDirection::Long => limit_price.safe_sub(buffer).map(Some),
PositionDirection::Short => limit_price.safe_add(buffer).map(Some),
}
} else {
Ok(None)
}
}
pub fn calculate_base_asset_amount_to_fill_up_to_limit_price(
order: &Order,
market: &PerpMarket,
limit_price: Option<u64>,
existing_base_asset_amount: Option<i64>,
) -> DriftResult<u64> {
let base_asset_amount_unfilled =
order.get_base_asset_amount_unfilled(existing_base_asset_amount)?;
let (max_trade_base_asset_amount, max_trade_direction) = if let Some(limit_price) = limit_price
{
// buy to right below or sell up right above the limit price
let adjusted_limit_price = match order.direction {
PositionDirection::Long => limit_price.safe_sub(market.amm.order_tick_size)?,
PositionDirection::Short => limit_price.safe_add(market.amm.order_tick_size)?,
};
math::amm_spread::calculate_base_asset_amount_to_trade_to_price(
&market.amm,
adjusted_limit_price,
order.direction,
)?
} else {
(base_asset_amount_unfilled, order.direction)
};
if max_trade_direction != order.direction || max_trade_base_asset_amount == 0 {
return Ok(0);
}
standardize_base_asset_amount(
min(base_asset_amount_unfilled, max_trade_base_asset_amount),
market.amm.order_step_size,
)
}
pub fn calculate_quote_asset_amount_for_maker_order(
base_asset_amount: u64,
fill_price: u64,
base_decimals: u32,
position_direction: PositionDirection,
) -> DriftResult<u64> {
let precision_decrease = 10_u128.pow(base_decimals);
match position_direction {
PositionDirection::Long => fill_price
.cast::<u128>()?
.safe_mul(base_asset_amount.cast()?)?
.safe_div(precision_decrease)?
.cast::<u64>(),
PositionDirection::Short => fill_price
.cast::<u128>()?
.safe_mul(base_asset_amount.cast()?)?
.safe_div_ceil(precision_decrease)?
.cast::<u64>(),
}
}
pub fn standardize_base_asset_amount_with_remainder_i128(
base_asset_amount: i128,
step_size: u128,
) -> DriftResult<(i128, i128)> {
let remainder = base_asset_amount
.unsigned_abs()
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?
.cast::<i128>()?
.safe_mul(base_asset_amount.signum())?;
let standardized_base_asset_amount = base_asset_amount.safe_sub(remainder)?;
Ok((standardized_base_asset_amount, remainder))
}
pub fn standardize_base_asset_amount(base_asset_amount: u64, step_size: u64) -> DriftResult<u64> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
base_asset_amount.safe_sub(remainder)
}
pub fn standardize_base_asset_amount_ceil(
base_asset_amount: u64,
step_size: u64,
) -> DriftResult<u64> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
Ok(base_asset_amount)
} else {
base_asset_amount.safe_add(step_size)?.safe_sub(remainder)
}
}
pub fn is_multiple_of_step_size(base_asset_amount: u64, step_size: u64) -> DriftResult<bool> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
Ok(remainder == 0)
}
pub fn standardize_price(
price: u64,
tick_size: u64,
direction: PositionDirection,
) -> DriftResult<u64> {
if price == 0 {
return Ok(0);
}
let remainder = price
.checked_rem_euclid(tick_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
return Ok(price);
}
match direction {
PositionDirection::Long => price.safe_sub(remainder),
PositionDirection::Short => price.safe_add(tick_size)?.safe_sub(remainder),
}
}
pub fn standardize_price_i64(
price: i64,
tick_size: i64,
direction: PositionDirection,
) -> DriftResult<i64> {
if price == 0 {
return Ok(0);
}
let remainder = price
.checked_rem_euclid(tick_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
return Ok(price);
}
match direction {
PositionDirection::Long => price.safe_sub(remainder),
PositionDirection::Short => price.safe_add(tick_size)?.safe_sub(remainder),
}
}
#[inline(always)]
pub fn apply_protected_maker_limit_price_offset(
price: u64,
direction: PositionDirection,
params: ProtectedMakerParams,
standardize: bool,
) -> DriftResult<u64> {
let min_offset = params
.tick_size
.checked_shl(3)
.ok_or(ErrorCode::MathError)?;
let limit_price_bps_divisor = if params.limit_price_divisor > 0 {
10000 / params.limit_price_divisor as u64
} else {
1000_u64 // 10bps
};
let price_offset = price
.safe_div(limit_price_bps_divisor)?
.max(min_offset)
.max(params.dynamic_offset)
.min(price / 20);
let price = match direction {
PositionDirection::Long => price.saturating_sub(price_offset).max(params.tick_size),
PositionDirection::Short => price.saturating_add(price_offset),
};
if standardize {
standardize_price(price, params.tick_size, direction)
} else {
Ok(price)
}
}
pub fn get_price_for_perp_order(
price: u64,
direction: PositionDirection,
post_only: PostOnlyParam,
amm: &AMM,
) -> DriftResult<u64> {
let mut limit_price = standardize_price(price, amm.order_tick_size, direction)?;
if post_only == PostOnlyParam::Slide {
let reserve_price = amm.reserve_price()?;
match direction {
PositionDirection::Long => {
let amm_ask = amm.ask_price(reserve_price)?;
if limit_price >= amm_ask {
limit_price = amm_ask.safe_sub(amm.order_tick_size)?;
}
}
PositionDirection::Short => {
let amm_bid = amm.bid_price(reserve_price)?;
if limit_price <= amm_bid {
limit_price = amm_bid.safe_add(amm.order_tick_size)?;
}
}
}
}
Ok(limit_price)
}
pub fn get_position_delta_for_fill(
base_asset_amount: u64,
quote_asset_amount: u64,
direction: PositionDirection,
) -> DriftResult<PositionDelta> {
Ok(PositionDelta {
quote_asset_amount: match direction {
PositionDirection::Long => -quote_asset_amount.cast()?,
PositionDirection::Short => quote_asset_amount.cast()?,
},
base_asset_amount: match direction {
PositionDirection::Long => base_asset_amount.cast()?,
PositionDirection::Short => -base_asset_amount.cast()?,
},
})
}
#[inline(always)]
pub fn should_expire_order(user: &User, user_order_index: usize, now: i64) -> DriftResult<bool> {
let order = &user.orders[user_order_index];
if order.status != OrderStatus::Open || order.max_ts == 0 || order.must_be_triggered() {
return Ok(false);
}
Ok(now > order.max_ts)
}
pub fn should_cancel_reduce_only_order(
order: &Order,
existing_base_asset_amount: i64,
step_size: u64,
) -> DriftResult<bool> {
let should_cancel = order.status == OrderStatus::Open
&& order.reduce_only
&& order.get_base_asset_amount_unfilled(Some(existing_base_asset_amount))? < step_size;
Ok(should_cancel)
}
pub fn order_breaches_maker_oracle_price_bands(
order: &Order,
oracle_price: i64,
slot: u64,
tick_size: u64,
margin_ratio_initial: u32,
is_prediction_market: bool,
) -> DriftResult<bool> {
let order_limit_price = order.force_get_limit_price(
Some(oracle_price),
None,
slot,
tick_size,
is_prediction_market,
None,
)?;
limit_price_breaches_maker_oracle_price_bands(
order_limit_price,
order.direction,
oracle_price,
margin_ratio_initial,
)
}
/// Cancel maker order if there limit price cross the oracle price sufficiently
/// E.g. if initial margin ratio is .05 and oracle price is 100, then maker limit price must be
/// less than 105 to be valid
pub fn limit_price_breaches_maker_oracle_price_bands(
order_limit_price: u64,
order_direction: PositionDirection,
oracle_price: i64,
margin_ratio_initial: u32,
) -> DriftResult<bool> {
let oracle_price = oracle_price.unsigned_abs();
let max_percent_diff = margin_ratio_initial;
match order_direction {
PositionDirection::Long => {
if order_limit_price <= oracle_price {
return Ok(false);
}
let percent_diff = order_limit_price
.safe_sub(oracle_price)?
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
if percent_diff >= max_percent_diff.cast()? {
// order cant be buying if oracle price is more than 5% below limit price
msg!(
"Limit Price Breaches Oracle for Long: {} >> {}",
order_limit_price,
oracle_price
);
return Ok(true);
}
Ok(false)
}
PositionDirection::Short => {
if order_limit_price >= oracle_price {
return Ok(false);
}
let percent_diff = oracle_price
.safe_sub(order_limit_price)?
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
if percent_diff >= max_percent_diff.cast()? {
// order cant be selling if oracle price is more than 5% above limit price
msg!(
"Limit Price Breaches Oracle for Short: {} << {}",
order_limit_price,
oracle_price
);
return Ok(true);
}
Ok(false)
}
}
}
pub fn validate_fill_price_within_price_bands(
fill_price: u64,
oracle_price: i64,
oracle_twap_5min: i64,
margin_ratio_initial: u32,
oracle_twap_5min_percent_divergence: u64,
is_prediction_market: bool,
direction: Option<PositionDirection>,
) -> DriftResult {
if is_prediction_market {
validate!(
fill_price <= MAX_PREDICTION_MARKET_PRICE,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Prediction Market Price Bands: (fill: {} >= oracle: {})",
fill_price,
PRICE_PRECISION_U64
)?;
return Ok(());
}
if let Some(direction) = direction {
if direction == PositionDirection::Long {
if fill_price < oracle_price.cast::<u64>()?
&& fill_price < oracle_twap_5min.cast::<u64>()?
{
return Ok(());
}
} else {
if fill_price > oracle_price.cast::<u64>()?
&& fill_price > oracle_twap_5min.cast::<u64>()?
{
return Ok(());
}
}
}
let max_oracle_diff = margin_ratio_initial.cast::<u128>()?;
let max_oracle_twap_diff = oracle_twap_5min_percent_divergence.cast::<u128>()?; // 50%
let percent_diff = fill_price
.cast::<i64>()?
.safe_sub(oracle_price)?
.cast::<i128>()?
.safe_mul(MARGIN_PRECISION_I128)?
.safe_div(oracle_price.cast::<i128>()?)?
.unsigned_abs();
let percent_diff_twap = fill_price
.cast::<i64>()?
.safe_sub(oracle_twap_5min)?
.cast::<i128>()?
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(oracle_twap_5min.cast::<i128>()?)?
.unsigned_abs();
validate!(
percent_diff < max_oracle_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle Price Bands: max_oracle_diff {} % , pct diff {} % (fill: {} , oracle: {})",
max_oracle_diff,
percent_diff,
fill_price,
oracle_price
)?;
validate!(
percent_diff_twap < max_oracle_twap_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle TWAP Price Bands: max_oracle_twap_diff {} % , pct diff {} % (fill: {} , twap: {})",
max_oracle_twap_diff,
percent_diff,
fill_price,
oracle_twap_5min
)?;
Ok(())
}
pub fn is_oracle_too_divergent_with_twap_5min(
oracle_price: i64,
oracle_twap_5min: i64,
max_divergence: i64,
) -> DriftResult<bool> {
let percent_diff = oracle_price
.safe_sub(oracle_twap_5min)?
.abs()
.safe_mul(PERCENTAGE_PRECISION_U64.cast::<i64>()?)?
.safe_div(oracle_twap_5min.abs())?;
let too_divergent = percent_diff >= max_divergence;
if too_divergent {
msg!("max divergence {}", max_divergence);
msg!(
"Oracle Price Too Divergent from TWAP 5min. oracle: {} twap: {}",
oracle_price,
oracle_twap_5min
);
}
Ok(too_divergent)
}
pub fn order_satisfies_trigger_condition(order: &Order, oracle_price: u64) -> DriftResult<bool> {
match order.trigger_condition {
OrderTriggerCondition::Above => Ok(oracle_price > order.trigger_price),
OrderTriggerCondition::Below => Ok(oracle_price < order.trigger_price),
_ => Err(print_error!(ErrorCode::InvalidTriggerOrderCondition)()),
}
}
pub fn is_new_order_risk_increasing(
order: &Order,
position_base_asset_amount: i64,
position_bids: i64,
position_asks: i64,
) -> DriftResult<bool> {
if order.reduce_only {
return Ok(false);
}
match order.direction {
PositionDirection::Long => {
if position_base_asset_amount >= 0 {
return Ok(true);
}
Ok(position_bids.safe_add(order.base_asset_amount.cast()?)?
> position_base_asset_amount.abs())
}
PositionDirection::Short => {
if position_base_asset_amount <= 0 {
return Ok(true);
}
Ok(position_asks
.safe_sub(order.base_asset_amount.cast()?)?
.abs()
> position_base_asset_amount)
}
}
}
pub fn is_order_position_reducing(
order_direction: &PositionDirection,
order_base_asset_amount: u64,
position_base_asset_amount: i64,
) -> DriftResult<bool> {
Ok(match order_direction {
// User is short and order is long
PositionDirection::Long if position_base_asset_amount < 0 => {
order_base_asset_amount <= position_base_asset_amount.unsigned_abs()
}
// User is long and order is short
PositionDirection::Short if position_base_asset_amount > 0 => {
order_base_asset_amount <= position_base_asset_amount.unsigned_abs()
}
_ => false,
})
}
pub fn validate_fill_price(
quote_asset_amount: u64,
base_asset_amount: u64,
base_precision: u64,
order_direction: PositionDirection,
order_limit_price: u64,
is_taker: bool,
) -> DriftResult {
let rounded_quote_asset_amount = if is_taker {
match order_direction {
PositionDirection::Long => quote_asset_amount.saturating_sub(1),
PositionDirection::Short => quote_asset_amount.saturating_add(1),
}
} else {
quote_asset_amount
};
let fill_price = calculate_fill_price(
rounded_quote_asset_amount,
base_asset_amount,
base_precision,
)?;
if order_direction == PositionDirection::Long && fill_price > order_limit_price {
msg!(
"long order fill price ({} = {}/{} * 1000) > limit price ({}) is_taker={}",
fill_price,
quote_asset_amount,
base_asset_amount,
order_limit_price,
is_taker
);
return Err(ErrorCode::InvalidOrderFillPrice);
}
if order_direction == PositionDirection::Short && fill_price < order_limit_price {
msg!(
"short order fill price ({} = {}/{} * 1000) < limit price ({}) is_taker={}",
fill_price,
quote_asset_amount,
base_asset_amount,
order_limit_price,
is_taker
);
return Err(ErrorCode::InvalidOrderFillPrice);
}
Ok(())
}
pub fn calculate_fill_price(
quote_asset_amount: u64,
base_asset_amount: u64,
base_precision: u64,
) -> DriftResult<u64> {
quote_asset_amount
.cast::<u128>()?
.safe_mul(base_precision as u128)?
.safe_div(base_asset_amount.cast()?)?
.cast::<u64>()
}
pub fn get_max_fill_amounts(
user: &User,
user_order_index: usize,
base_market: &SpotMarket,
quote_market: &SpotMarket,
is_leaving_drift: bool,
) -> DriftResult<(Option<u64>, Option<u64>)> {
let direction: PositionDirection = user.orders[user_order_index].direction;
match direction {
PositionDirection::Long => {
let max_quote = get_max_fill_amounts_for_market(user, quote_market, is_leaving_drift)?
.cast::<u64>()?;
Ok((None, Some(max_quote)))
}
PositionDirection::Short => {
let max_base = standardize_base_asset_amount(
get_max_fill_amounts_for_market(user, base_market, is_leaving_drift)?
.cast::<u64>()?,
base_market.order_step_size,
)?;
Ok((Some(max_base), None))
}
}
}
fn get_max_fill_amounts_for_market(
user: &User,
market: &SpotMarket,
is_leaving_drift: bool,
) -> DriftResult<u128> {
let position_index = user.get_spot_position_index(market.market_index)?;
let token_amount = user.spot_positions[position_index].get_signed_token_amount(market)?;
get_max_withdraw_for_market_with_token_amount(market, token_amount, is_leaving_drift)
}
pub fn find_maker_orders(
user: &User,
direction: &PositionDirection,
market_type: &MarketType,
market_index: u16,
valid_oracle_price: Option<i64>,
slot: u64,
tick_size: u64,
is_prediction_market: bool,
protected_maker_params: Option<ProtectedMakerParams>,
) -> DriftResult<Vec<(usize, u64)>> {
let mut orders: Vec<(usize, u64)> = Vec::with_capacity(32);
for (order_index, order) in user.orders.iter().enumerate() {
if order.status != OrderStatus::Open {
continue;
}
// if order direction is not same or market type is not same or market index is the same, skip
if order.direction != *direction
|| order.market_type != *market_type
|| order.market_index != market_index
{
continue;
}
// if order is not limit order or must be triggered and not triggered, skip
if !order.is_limit_order() || (order.must_be_triggered() && !order.triggered()) {
continue;
}
let limit_price = order.force_get_limit_price(
valid_oracle_price,
None,
slot,
tick_size,
is_prediction_market,
protected_maker_params,
)?;
orders.push((order_index, limit_price));
}
Ok(orders)
}
pub fn calculate_max_perp_order_size(
user: &User,
position_index: usize,
market_index: u16,
direction: PositionDirection,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<u64> {
let margin_context = MarginContext::standard(MarginRequirementType::Initial).strict(true);
// calculate initial margin requirement
let margin_calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
margin_context,
)?;
let user_custom_margin_ratio = user.max_margin_ratio;
let perp_position_margin_ratio = user.perp_positions[position_index].max_margin_ratio as u32;
let user_high_leverage_mode = user.is_high_leverage_mode(MarginRequirementType::Initial);
let is_isolated_position = user.perp_positions[position_index].is_isolated();
let free_collateral_before = if is_isolated_position {
margin_calculation
.get_isolated_free_collateral(market_index)?
.cast::<i128>()?
} else {
margin_calculation
.get_cross_free_collateral()?
.cast::<i128>()?
};
let perp_market = perp_market_map.get_ref(&market_index)?;
let oracle_price_data_price = oracle_map.get_price_data(&perp_market.oracle_id())?.price;
let quote_spot_market = spot_market_map.get_ref(&perp_market.quote_spot_market_index)?;
let quote_oracle_price = oracle_map
.get_price_data("e_spot_market.oracle_id())?
.price
.max(
quote_spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
);
drop(quote_spot_market);
let perp_position: &PerpPosition = &user.perp_positions[position_index];
let (worst_case_base_asset_amount, worst_case_liability_value) = perp_position
.worst_case_liability_value(oracle_price_data_price, perp_market.contract_type)?;
let margin_ratio = perp_market
.get_margin_ratio(
worst_case_base_asset_amount.unsigned_abs(),
MarginRequirementType::Initial,
user_high_leverage_mode,
)?
.max(user_custom_margin_ratio)
.max(perp_position_margin_ratio);
let mut order_size_to_reduce_position = 0_u64;
let mut free_collateral_released = 0_i128;
// account for order flipping worst case base asset amount
if worst_case_base_asset_amount < 0 && direction == PositionDirection::Long {
order_size_to_reduce_position = worst_case_base_asset_amount
.abs()
.cast::<i64>()?
.safe_sub(perp_position.open_bids)?
.max(0)
.unsigned_abs();
let existing_position_margin_requirement = worst_case_liability_value
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?;
free_collateral_released = existing_position_margin_requirement.cast()?;
} else if worst_case_base_asset_amount > 0 && direction == PositionDirection::Short {
order_size_to_reduce_position = worst_case_base_asset_amount
.cast::<i64>()?
.safe_add(perp_position.open_asks)?
.max(0)
.unsigned_abs();
let existing_position_margin_requirement = worst_case_liability_value
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?;
free_collateral_released = existing_position_margin_requirement.cast()?;
}
// if user has no free collateral, just return the order size to reduce position
if free_collateral_before <= 0 {
return standardize_base_asset_amount(
order_size_to_reduce_position,
perp_market.amm.order_step_size,
);
}
let oracle_price =
if !perp_market.is_prediction_market() || direction == PositionDirection::Long {
oracle_price_data_price
} else {
MAX_PREDICTION_MARKET_PRICE_I64.safe_sub(oracle_price_data_price)?
};
let calculate_order_size_and_margin_ratio = |margin_ratio: u32, margin_ratio_delta: i32| {
let free_collateral_from_margin_ratio_delta = worst_case_base_asset_amount
.safe_mul(oracle_price.cast()?)?
.safe_div(BASE_PRECISION_I128)?
.safe_mul(margin_ratio_delta.cast()?)?
.safe_div(MARGIN_PRECISION_I128.cast()?)?;
let new_order_size = free_collateral_before
.safe_add(free_collateral_released)?
.safe_sub(free_collateral_from_margin_ratio_delta)?
.safe_sub(OPEN_ORDER_MARGIN_REQUIREMENT.cast()?)?
.safe_mul(BASE_PRECISION_I128)?
.safe_mul(MARGIN_PRECISION_U128.cast()?)?
.safe_div(margin_ratio.cast()?)?
.safe_mul(PRICE_PRECISION_I128)?
.safe_div(oracle_price.cast()?)?
.safe_mul(PRICE_PRECISION_I128)?
.safe_div(quote_oracle_price.cast()?)?
.safe_div(QUOTE_PRECISION_I128)?
.cast::<u64>()?;
let worst_case_base_asset_amount =
worst_case_base_asset_amount.safe_add(new_order_size.cast()?)?;
let new_margin_ratio = perp_market
.get_margin_ratio(
worst_case_base_asset_amount.unsigned_abs(),
MarginRequirementType::Initial,
user_high_leverage_mode,
)?
.max(user_custom_margin_ratio)
.max(perp_position_margin_ratio);
Ok((new_order_size, new_margin_ratio))
};
let mut order_size = 0_u64;
let mut updated_margin_ratio = margin_ratio;
let mut margin_ratio_delta = 0;
for _ in 0..6 {
let (new_order_size, new_margin_ratio) =
calculate_order_size_and_margin_ratio(updated_margin_ratio, margin_ratio_delta)?;
order_size = new_order_size;
if new_margin_ratio == updated_margin_ratio {
break;
}
margin_ratio_delta = new_margin_ratio
.cast::<i32>()?
.safe_sub(margin_ratio.cast::<i32>()?)?;
updated_margin_ratio = new_margin_ratio;
}
standardize_base_asset_amount(
order_size.safe_add(order_size_to_reduce_position)?,
perp_market.amm.order_step_size,
)
}
#[allow(clippy::unwrap_used)]
pub fn calculate_max_spot_order_size(
user: &User,
market_index: u16,
direction: PositionDirection,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<u64> {
// calculate initial margin requirement
let MarginCalculation {
margin_requirement,
total_collateral,
..
} = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Initial).strict(true),
)?;
let user_custom_margin_ratio = user.max_margin_ratio;
let user_custom_liability_weight = user.max_margin_ratio.saturating_add(SPOT_WEIGHT_PRECISION);
let user_custom_asset_weight = SPOT_WEIGHT_PRECISION.saturating_sub(user_custom_margin_ratio);
let mut order_size_to_flip = 0_u64;
let free_collateral = total_collateral.safe_sub(margin_requirement.cast()?)?;
let spot_market = spot_market_map.get_ref(&market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
let twap = spot_market
.historical_oracle_data
.last_oracle_price_twap_5min;
let strict_oracle_price = StrictOraclePrice::new(oracle_price_data.price, twap, true);
let max_oracle_price = strict_oracle_price.max();
let spot_position = user.get_spot_position(market_index)?;
let signed_token_amount = spot_position.get_signed_token_amount(&spot_market)?;
let [bid_simulation, ask_simulation] = spot_position
.simulate_fills_both_sides(
&spot_market,
&strict_oracle_price,
Some(signed_token_amount),
MarginRequirementType::Initial,
)?
.map(|simulation| {
simulation
.apply_user_custom_margin_ratio(
&spot_market,
strict_oracle_price.current,
user_custom_margin_ratio,
)
.unwrap()
});
let OrderFillSimulation {
token_amount: mut worst_case_token_amount,
..
} = OrderFillSimulation::riskier_side(ask_simulation, bid_simulation);
// account for order flipping worst case